javascript tutorial - [5 Solutions] “for…in” - javascript - java script - javascript array
Problem
Why is using “for…in” with array iteration a bad idea?
Solution 1:
The reason is that one construct:
Solution 2:
can sometimes be totally different from the other:
Solution 3:
Also consider that JavaScript libraries might do things like this, which will affect any array we create:
Solution 4:
Because for...in enumerates through the object that holds the array, not the array itself. If WE add a function to the arrays prototype chain, that will also be included. I.e.
And since we can never be sure that nothing will be added to the prototype chain just use a for loop to enumerate the array:
Solution 5:
In addition to the other problems, the "for..in" syntax is probably slower, because the index is a string, not an integer.