Javascript For-each/for-in Loop Changing Element Types
Solution 1:
I think you misunderstand what JavaScript for...in
does. It does not iterate over the array elements. It iterates over object properties. Objects in JavaScript are kind of like dictionaries or hashes in other languages, but keyed by strings. Arrays in particular are implemented as objects which have properties that are integers from 0
to N-1
- however, since all property names are strings, so are the indices, deep down.
Now let's take a bit different example than [0]
, since here index coincides with the value. Let's discuss [2]
instead.
Thus, [2]
is, if we ignore the stuff we inherit from Array
, pretty much the same as { "0": 2 }
.
for..in
will iterate over property names, which will pick up the "0"
, not the 2
.
Now, how to iterate over Array
s then, you ask? The usual way is:
var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
var el = array[i];
// ...
}
Solution 2:
This is a repeat of Why is using "for...in" with array iteration a bad idea?
Solution 3:
The for-in
statement enumerates the properties of an object. In your case element
is the name of the property and that is always a string.
Post a Comment for "Javascript For-each/for-in Loop Changing Element Types"