Saturday 1 February 2014

Why is using “for…in” with array iteration such a bad idea?

The reason is that one construct...
var a = [];
a
[5] = 5; // Perfectly legal JavaScript that resizes the array.

for (var i=0; i<a.length; i++) {
// Iterates over numeric indexes from 0 to 5, as everyone expects.
}
can sometimes be totally different from the other...
var a = [];
a
[5] = 5;
for (var x in a) {
// Shows only the explicitly set index of "5", and ignores 0-4
}
Also consider that JavaScript libraries might do things like this, which will affect any array you create:
// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;

// Now you have no idea what the below code will do.
var a = [1,2,3,4,5];
for (var x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'.
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More