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

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

提交回复
热议问题