for..in should not be used to iterate over an Array where index order is important.
Array indexes are just enumerable properties with integer names and are otherwise
identical to general Object properties.
There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties,
including those with non–integer names and those that are inherited.
Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order.
Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop)
when iterating over arrays where the order of access is important.
If new properties are
added to the object being enumerated during enumeration, the newly added properties are not guaranteed to
be visited in the active enumeration. A property name must not be visited more than once in any enumeration.
Let's talk about with example, if we are using a library, which uses.
Array.prototype.maxLimit = 100000;
This property iterate over the for .. in loop .
Another version of your code to explain for .. in loop
var foo = [3,4,5];
for ( var i in ( alert( JSON.stringify(foo)) || foo ) ) {
if ( i == 1 ) {
foo.unshift(6,6);
}
console.log('item: '+foo[i] , i , foo.length );
}
The alert popup only once
for-into iterate your array instead offor. This causes a variety of problems in JavaScript, and you've come across one. Sincefor-indoesn't guarantee any particular order of enumeration, it's including the unshifted value. A different browser may not include it... and both would be correct.unshiftis used.