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 ?

3
  • 4
    Show us the code that creates your list. Commented Aug 7, 2013 at 12:18
  • 1
    I'd recommand not using for in for arrays (see stackoverflow.com/questions/500504/… ) Commented Aug 7, 2013 at 12:19
  • I recommend to read the MDN documentation about for...in. It tells you what the problem is. Commented Aug 7, 2013 at 12:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It it helped, it would be great to mark this answer as answer :-)
Was waiting for the remaining time to mark an answer as the right answer to go off ;)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.