欢迎光临
我们一直在努力

js遍历数组和遍历对象的区别

[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>
[/js]

赞(0) 打赏
未经允许不得转载:程序开发爱好者 » js遍历数组和遍历对象的区别
分享到: 更多 (0)

网站设计及开发、微应用及微网站开发、微信公众平台开发、 HTML5手机网站开发、网络整合营销、APP开发、软件开发及企业电商服务

联系我们