for (var i in test)
enumerates all properties of the test
array (remember an Array is an Object and can have arbitrary non-numeric properties too). This includes not only the indexes of the array, but also any enumerable properties that someone else might have added to the Array object. This is generally considered the wrong way to enumerate an array. This structure is made to enumerate all properties of an object, not only the array indexes of an array.
Instead, you can use any of these:
for (var i = 0; i < test.length; i++)
test.forEach(fn);
test.every(fn);
test.some(fn);
These will only enumerate actual array items, not other properties added to the array.
On sparse arrays (where not all items have been initialized), the for
loop will visit every item (even the uninitialized items), whereas the others will skip the uninitialized items.
The fact that you are seeing the equal
property show up in your enumeration means that someone has added an enumerable property to the Array object and thus it shows up with the for (var i in test)
form of enumeration.
In ES6, you can also use the of
iteration technique and this will be safe from the non-array element properties and will return the same items that .forEach()
will return. Note, it also differs from in
because it delivers the actual array values, not the array indexes:
var test = [4, 7, 13];
test.whatever = "foo";
for (var item of test) {
console.log(item); // 4, 7, 13
}