6

I just experienced the strangest thing, this is the code I'm actually using :

for (iter in data.List) {
    console.log(iter);
}

As you would expect, the log should give the number of each row (0, 1, 2...), instead it gives me this :

0
1
2
remove

Knowing that my array only has 3 rows

Did anybody ever encountred this ?

Mehdiway
  • 10,337
  • 8
  • 36
  • 68
  • 4
    Show us the code that creates your list. – Aleks G Aug 07 '13 at 12:18
  • 1
    I'd recommand not using `for in` for arrays (see http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea ) – Py. Aug 07 '13 at 12:19
  • I recommend to read the [MDN documentation about `for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). It tells you what the problem is. – Felix Kling Aug 07 '13 at 12:20

2 Answers2

9

Basically, the problem is that you are iterating through your array using a for in loop, which is not meant for iteratung through arrays. Its intent is to iterate through all properties of an object, and apparently there is a property called remove on your array.

For more details on why for in is a bad idea when it comes to arrays, see Why is using "for...in" with array iteration a bad idea?.

As solution, I'd suggest to use an indexed for loop. This type of loop does not care about properties, hence you are fine. So it basically comes down to a very classical:

for (var i = 0; i < data.List; i++) {
  console.log(data.List[i]);
}

By the way: You should not uppercase anything in JavaScript, unless it's a constructor function. Hence it should be data.list.

PS: A nice read when it comes to arrays and (mis-)using them, read Fun with JavaScript Arrays, a quite good read.

Community
  • 1
  • 1
Golo Roden
  • 140,679
  • 96
  • 298
  • 425
6

Yes, that is how for..in works in JavaScript. It enumerates over all object properties (not Array indexes). Simple solution: don't use for..in on Arrays, because that's not what it is for.

RoToRa
  • 37,635
  • 12
  • 69
  • 105