Reputation:
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);
}
Upvotes: 12
Views: 1399
Reputation: 162831
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);
}
Upvotes: 15
Reputation: 1614
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
.Upvotes: 4
Reputation: 388023
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.
Upvotes: 0
Reputation: 827724
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?
Array.prototype
or Object.prototype
.More details on a recently answered question:
Upvotes: 3
Reputation: 993961
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.
Upvotes: 4