For a loop in the array read 'remove'?

I just experienced the strangest thing, this is the code I actually use:

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

As expected, the log should indicate the number of each line (0, 1, 2 ...), instead it gives me the following:

 0 1 2 remove 

Knowing that my array has only 3 rows

Has anyone ever come across this?

+6
source share
2 answers

Basically the problem is that you iterate through your array using a for in loop, which is not designed to iterate through arrays. Its purpose is to iterate over all the properties of the object, and there appears to be a property in your array called remove .

For more information about 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 a solution, I would suggest using an indexed for loop. This type of loop does not care about properties, therefore you are fine. So this basically boils down to very classic:

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

By the way: you shouldn’t make out anything in JavaScript, unless it is a constructor function. Therefore, it should be data.list .

PS: nice to read when it comes to arrays and (incorrectly) using them, read Fun with JavaScript Arrays , nice to read.

+9
source

Yes, this is how for..in works in JavaScript. It lists all the properties of an object (not Array indexes). A simple solution: do not use for..in in arrays, because this is not what it is intended for.

+6
source

Source: https://habr.com/ru/post/951215/


All Articles