2

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.

Grace Note
  • 3,205
  • 4
  • 35
  • 55
disc0dancer
  • 9,185
  • 11
  • 36
  • 46
  • 1
    Not an answer to your question, but you may want to use hasOwnPropertyin your for...in loops: http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object – Joeri Sebrechts Jul 03 '09 at 04:46

1 Answers1

13

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.

Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
  • 1
    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. – Matthew Crumley Jul 03 '09 at 04:48