开发者

Why does javascript turn array indexes into strings when iterating?

This Javascript logic puzzles me. I'm creating an array and setting the first element of it to a number. When I interate through it using开发者_JS百科 a "for" loop Javascript turns the array key into a string. Why? I want it to stay a number.

stuff = [];
stuff[0] = 3;

for(var x in stuff) {
    alert(typeof x);
}


It's because you're looping through the array using for...in which is generally used for looping over properties of objects. The javascript engine is probably casting to a string because the string type is suitable for names of object properties.

Try this more traditional approach:

stuff = [];
stuff[0] = 3;

for(var i=0; i<stuff.length; i++) {
    var x = stuff[i];
    alert(typeof x);
}


for..in is not designed to iterate over Arrays. Use a C-style for loop instead.

Reference: MDC


The for .. in loop in Javascript iterates through the properties of the object. In Javascript, property names are strings and arrays are just objects with a bunch of properties that happen to look like numbers.


The for...in statement should be used to iterate over object properties, for Arrays use a simple for loop:

var stuff = [];
stuff.push(3);

for(var i = 0; i < stuff.length; i++) {
  alert(stuff[i]);
}

Why shouldn't use for...in with arrays?

  1. It crawls up the prototype chain, it will iterate over properties defined up in the Array.prototype or Object.prototype.
  2. The order of iteration is not guaranteed anyhow.

More details on a recently answered question:

  • Strange behavior in Javascript enhanced for…in loop


Avoid for-in in performance-critical functions.

  • The for-in loop requires the script engine to build a list of all the enumerable properties, and check for duplicates in that list, before it can start the enumeration.
  • The for-in loop breaks when you extend Array object using prototype.


The problem is that it is very easy in JavaScript to switch to associative arrays, which are in fact not arrays but objects. The for..in loop however works on objects, which indices are strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜