JavaScript For

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.


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];
  // ...
}

这是重复的为什么使用“for ... in”与数组迭代是一个坏主意?


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.

链接地址: http://www.djcxy.com/p/70020.html

上一篇: 我应该为JavaScript数组和对象使用哪个循环?

下一篇: JavaScript的