So I am using this in IE8:
var hi=["hi", "lo", "foo", "bar"];
for(i in hi){console.log(i)};
//WTF is that indexOf i value?
LOG: 0
LOG: 1
LOG: 2
LOG: 3
LOG: indexOf
undefined
In chrome and others, I’ll just get 0-3, no mysterious “indexOf” thing. Why and what’s the fix?
Don’t use
for...infor arrays. It’s best to use the traditionalforloop in that case.The reason is because
for...inlooks at the array as an object, and therefore properties likeindexOforlengthmay be included in the loop. The normalforloop only deals with numeric keys, so this problem is avoided.On a side note, unwanted properties could show up when iterating over plain objects as well (as others have noted, properties you add to the object’s prototype will show up). You can get around this by writing your
for...inloops this way:To be clear though: you still shouldn’t use this method on arrays.