Which for loop should I use for JavaScript arrays and objects?

This question already has an answer here:

  • Why is using “for…in” with array iteration a bad idea? 25 answers

  • I made a jsperf for you :

    http://jsperf.com/for-vs-for-in43

    Basicly, it is testing perfomance and you can see a huge performance drop when using for(var i in array) .

    That being said, you souldn't drop the for for for in .


    should I dump for

    You shouldn't. for..in when used to loop arrays doesn't care about the index and it will list properties attached to the object as well. Stick to for for arrays and for..in for objects.

    An excerpt from the MDN:

    for..in should not be used to iterate over an Array where index order is important... There is no guarantee that for..in will return the indexes in any particular order and it will return all enumerable properties...

    As for the performance, I wouldn't worry about it, because for..in to loop indexed arrays is obviously not recommended.


    can't use for (i=0; ... ) for object properties, but I can use for (var in ...) for arrays, because arrays are objects too.

    You should use for as the other answers already state.

    But you can use Object.keys(yourObject) to list the object's keys as an array, then use the for loop on that array.

    var keys = Object.keys(myObject);
    for(var i = 0, key; key = keys[i]; i++) {
        //...
    }
    
    链接地址: http://www.djcxy.com/p/70022.html

    上一篇: 一个基本的区别

    下一篇: 我应该为JavaScript数组和对象使用哪个循环?