首页 > 代码库 > js遍历数组和遍历对象的区别
js遍历数组和遍历对象的区别
来源:http://www.cnblogs.com/yun007/archive/2013/06/06/3121393.html
<script> //----------------for用来遍历数组对象-- var i,myArr = [1,2,3]; for (var i = 0; i < myArr.length; i++) { console.log(i+":"+myArr[i]); };
//输出结果为:
0:1
1:2
2:3
//---------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]); }; } //输出结果为: 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]); } }
//输出结果为: hands:2,legs:2,heads:1
</script>
js遍历数组和遍历对象的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。