JS中for...in循环的坑及遍历数组的方式对比

JavaScript中有很多遍历数组的方式,比较常见的是for(var i=0;i<arr.length;i++){},以及for...in...循环等,这些遍历都有各自的优缺点,下面来看看各种JS的遍历对比:

1.for...in...

1).index索引为字符串型数字,不能直接进行几何运算。

2).遍历顺序有可能不是按照实际数组的内部顺序。

3).使用for in会遍历数组所有的可枚举属性,包括原型。例如上栗的原型方法method和name属性。

Array.prototype.myfun=function(){
    alert('myfun');
}    
var arr = [0,1,2,3];

for(var i in arr){
    console.log(arr[i]);
}

console.log(Array.prototype)

猜你喜欢

转载自www.cnblogs.com/wangxiayun/p/10194806.html