Saturday, February 5, 2011

Javascript for/in loops through properties, not indexes and returns strings.

Ok, I have this code:

var room = [ { time: 0, people: 0 } ];

and then:

time = 5;
for( var i in room ) {
  if( room[i].time < time ){
    spliceIndex = i + 1;
  }
}
console.log(spliceIndex);

And the console reads: 01 - Which means the 1 is concatenated which further means that i is a string, and not an integer as expected. Casting the index to integer fixed the problems, but I was banging my head for hours.... Can anyone explain why is this happening? I get this on Firefox 3.5 and Safari 4.

  • Because for-in lists object properties, not array indexes. Object properties are strings, and array indexes show up as properties, only they are numeric strings.

    Discodancer : :) nobody said that in the javascipt books i read. thanks.
    Matthew Crumley : That's why it's not a good idea to use a "for in" loop on arrays. They iterate over *all* the array's properties (except the built-in ones, which are non-enumerable), including string properties and properties inherited from Array.prototype.

0 comments:

Post a Comment