js遍歷數組和遍歷對象的區別


<script>
    //----------------for用來遍歷數組對象--
    var i,myArr = [1,2,3]; for (var i = 0; i < myArr.length; i++) { console.log(i+":"+myArr[i]); }; //---------for-in 用來遍歷非數組對象
    var man ={hands:2,legs:2,heads:1}; //為所有的對象添加clone方法,即給內置原型(object,Array,function)增加原型屬性,該方法很強大,也很危險
    if(typeof Object.prototype.clone ==="undefined"){ Object.prototype.clone = function(){}; } //     for(var i in man){ if (man.hasOwnProperty(i)) { //filter,只輸出man的私有屬性
            console.log(i,":",man[i]); }; } //輸出結果為print hands:2,legs:2,heads:1

    for(var i in man) {//不使用過濾
        console.log(i,":",man[i]); } //輸出結果為
    //hands : 2 index.html:20
    //legs : 2 index.html:20
    //heads : 1 index.html:20
    //clone : function (){} 
    for(var i in man) { if(Object.prototype.hasOwnProperty.call(man,i)) { //過濾
            console.log(i,":",man[i]); } }
 //輸出結果為print hands:2,legs:2,heads:1
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM