为什么for in循环不适合用于数组

首先一点无关的,使用(var i in a) 而不是( i in a),除非你想创建全局变量。

 

 

第二点,for in 循环会忽略空的数组

var a = [];



a[5] = 5; // Perfectly legal JavaScript that resizes the array.



 



for (var i=0; i<a.length; i++) {



    // Iterates over numeric indexes from 0 to 5, as everyone expects.



}



 



var a = [];



a[5] = 5;



for (var x in a) {



    // Shows only the explicitly set index of "5", and ignores 0-4



}

 

 

第三,for in循环会对prototype属性进行循环。

// Somewhere deep in your JavaScript library...



Array.prototype.foo = 1;



 



// Now you have no idea what the below code will do.



var a = [1,2,3,4,5];



for (var x in a){



    // Now foo is a part of EVERY array and



    // will show up here as a value of 'x'.



}

 

 

最后一点,下面是最简单也是最快最好的方法

for(var i = 0, length = array.length; i < length; i++)

 

 

总而言之,如果你想迭代循环一个对象的key,使用

for (var key in object)

如果你想迭代循环一个数组的元素,那么,使用

for(var i = 0, length = array.length; i < length; i++)

你可能感兴趣的:(for)