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 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.

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

上一篇: JavaScript for ... in和vs for

下一篇: 为什么JavaScript在迭代时将数组索引转换为字符串?