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

前端 未结 5 912
醉酒成梦
醉酒成梦 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: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 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.

提交回复
热议问题