问题
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.
回答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];
// ...
}
回答2:
This is a repeat of Why is using "for...in" with array iteration a bad idea?
回答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.
来源:https://stackoverflow.com/questions/6101817/javascript-for-each-for-in-loop-changing-element-types