While testing some JavaScrpt code in IE8 I’m experiencing some strange behaviour when doing a simple for..in loop:
var categories = ['for', 'bar', 'steam'];
for(var key in categories) {
console.log(key);
}
Outputs:
0
1
2
forEach
map
filter
reduce
indexOf
end
Which includes the Array prototype functions, right? That’s definitely not the way it should work. Why is that?
Btw, it works of course when changing the loop to for (var key=0; key < categories.length, key++).
That’s because you are probably using a library that extends
Array.prototype. The reason it doesn’t happen in other browsers is that they already support those methods natively. Since IE doesn’t support it, there’s some code that adds it in JS, which makes the methods enumerable.That’s one of the reasons why you shouldn’t use
for inwith arrays.The other is the fact that
for indoes not guarantee order of iteration, and though it does work in most browsers, it’s explicitly left as undefined behavior by the specification. John Resig himself filed a bug against chrome http://code.google.com/p/chromium/issues/detail?id=883 and it was closed as won’t fix, since there’s no requirement that properties need to be orderedStick to using a standard loop