Possible Duplicate:
JavaScript “For …in” with Arrays
I'm trying to use the for-in syntax to loop through an array of numbers. Problem is, those numbers are getting converted to strings.
for(var element in [0]) {
document.write(typeof(element)); // outputs "string"
}
Is this standard behavior? I can think of a bunch of ways to work around it, but I'm really just looking for an explaination, to expand my understanding of JavaScript.
This is a repeat of Why is using "for...in" with array iteration a bad idea?
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 from0
toN-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 fromArray
, pretty much the same as{ "0": 2 }
.for..in
will iterate over property names, which will pick up the"0"
, not the2
.Now, how to iterate over
Array
s then, you ask? The usual way is:The
for-in
statement enumerates the properties of an object. In your caseelement
is the name of the property and that is always a string.