user229407
user229407

Reputation:

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

Upvotes: 12

Views: 1399

Answers (6)

Asaph
Asaph

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

pramodc84
pramodc84

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

poke
poke

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

Christian C. Salvad&#243;
Christian C. Salvad&#243;

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?

  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:

Upvotes: 3

Greg Hewgill
Greg Hewgill

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

jonchang
jonchang

Reputation: 1544

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

Reference: MDC

Upvotes: 5

Related Questions