13

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);
}

6 Answers 6

16

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);
}
Sign up to request clarification or add additional context in comments.

Comments

6

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

Reference: MDC

Comments

5

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.

Comments

4

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.

Comments

3

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:

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.