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>
相關文章
相關標籤/搜索