for in
is a common Javascript trap. Instead of behaving like a foreach
from other languages, it actualy enumerates all properties in a given object.
Since Javascript Arrays happen to have a property for each index using for in
works sometimes, but as you have seen, it also enumerates any other properties you add. Another issue is that the for in
is not guaranteed to go through the properties in any particular order, so your results can vary depending on which browser/runtime you use.
It is safer, then, to just use a boring for
loop instead. There are many for
loop idioms in Javascript, so I will list some:
Regular for loop:
for(i=0; i<arr.length; i++){
Regular loop, caching the length:
for(i=0, n=arr.length; i<n; i++){
Loops over arrays of objects/NodeLists:
for(i=0; obj=arr[i]; i++){ //this works as long as the array has no falsy values
foo(obj)