Luka Yu
Luka Yu

Reputation: 31

for ( key in array) loops over array prototype

I don't know how to word this problem exactly but I found this extremely wired.

Basically I did this test in chrome's developer tool console.

for (var request in [0,1,2]) { console.log(request);}

0
1
2
compare 

the last four lines are all outputs from the for loop. during the for loop, request got the value compare.

I wonder if this is a bug in chrome.

Upvotes: 0

Views: 113

Answers (4)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

As others pointed out for .. in is not the best way to iterate thru array. If you insist on using it for some reason - use hasOwnProperty method to determine that property indeed belongs to the array:

var arr = [0,1,2];

for (var request in arr ) { 
    if (arr.hasOwnProperty(request)) console.log(request);
}

Upvotes: 0

tobibeer
tobibeer

Reputation: 500

in your case, the global "object-prototype" as a compare function declared for it, e.g...

object.prototype.compare = function (a,b) {return a === b}

...and so, whenever you iterate an object (an array being one kind of object) you also iterate over the "compare" function of it's prototype... which is a "member" of it.

Upvotes: 0

Joseph Hopkins
Joseph Hopkins

Reputation: 117

You're best off using an indexed for loop. For..in also enumerates over inherited properties etc.

var request = [0,1,2];
for (var i = 0; i < request.length; i++) {
   console.log(request[i]);
}

The top answer to this question:

stackoverflow previous answer

puts it better than I could:

Upvotes: 1

Alnitak
Alnitak

Reputation: 339917

for ... in ... iterates over the enumerable properties of an object, and is not intended for array indices. Array indices are also enumerable properties, but as you've discovered anything unsafely added to Array.prototype will be returned too.

To safely add a (non-enumerable) method to Array.prototype in ES5 browsers you can use Object.defineProperty, e.g.:

Object.defineProperty(Array.prototype, 'compare', {
    value: function() {
        ...
    }
});

This will stop for ... in from breaking, but it's still the wrong tool for the job when the variable of interest is an array.

Upvotes: 2

Related Questions