JavaScript For-each/For-in loop changing element t

2019-07-14 12:33发布

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.

3条回答
相关推荐>>
3楼-- · 2019-07-14 13:16

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 Arrays then, you ask? The usual way is:

var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
  var el = array[i];
  // ...
}
查看更多
甜甜的少女心
4楼-- · 2019-07-14 13:23

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.

查看更多
登录 后发表回答