Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?

前端 未结 5 877
醉酒成梦
醉酒成梦 2020-11-27 12:47

Given a simple zero based, numerically indexed array:

var list = [\'Foo\', \'Bar\', \'Baz\'];

Many times, I have noticed that when someone

相关标签:
5条回答
  • 2020-11-27 13:22

    If you use for/in like that, item enumerates through string values "0", "1", ..., so not the actual objects in the list. So the the 'item' in the first snippet is more like the i in the second snippet,not the item. Furthermore string values are enumerated where you'd expect numbers. And you get in trouble when you properties to the list, like array.ID = "a123", as they will get enumerated also.

    But with these downsides, I still think the syntax is very useful, if your team is aware of what it does.

    0 讨论(0)
  • 2020-11-27 13:23

    First, the order of the loop is undefined for a for...in loop, so there's no guarantee the properties will be iterated in the order you want.

    Second, for...in iterates over all enumerable properties of an object, including those inherited from its prototype. In the case of arrays, this could affect you if your code or any library included in your page has augmented the prototype of Array, which can be a genuinely useful thing to do:

    Array.prototype.remove = function(val) {
        // Irrelevant implementation details
    };
    
    var a = ["a", "b", "c"];
    
    for (var i in a) {
        console.log(i);
    }
    
    // Logs 0, 1, 2, "remove" (though not necessarily in that order)
    
    0 讨论(0)
  • 2020-11-27 13:28

    Speed?

    for(..;..;..) loop proved to be 36 times faster than for .. in when I tested it here.

    Link courtesy this SO answer

    0 讨论(0)
  • 2020-11-27 13:35

    Add list.foo = bar; and try to use simple for. If you don't use some libraries(like prototypeJs) and don't add any new properties to array object - you can use simple for-statement.

    0 讨论(0)
  • 2020-11-27 13:42

    for ... in ... doesn't return items of list, but instead enumerates array properties.

    For that reason alone, it cannot act as a replacement of for (i=0; i<arr.length; i++) loop.

    The appropriate alternative is for ... of ... construct. It enumerates values of an iterable object, such as an array. You can read more about it on MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

    It's supported by the relevant modern browsers (Internet Explorer doesn't count, with it being replaced by Microsoft Edge). If you can afford not supporting older browsers, it's probably the way to go. You can check the convenient browser support table at the end of aforelinked MDN page to see which browser versions actually allow for ... of ... usage.

    0 讨论(0)
提交回复
热议问题