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