I have got an array from which some items are going to be removed; but some loops are still running on them, so I want to simply skip the places where I remove my objects
I know that the syntax for(i in array) should do this because it iterates on the index, but how should I remove my items then ? Because when i do array[4] = null, my for just doesn't care and goes on trying to use the value at 4.
I also tried to check if !null but without success... thank you
I have got an array from which some items are going to be removed; but some loops are still running on them, so I want to simply skip the places where I remove my objects
I know that the syntax for(i in array) should do this because it iterates on the index, but how should I remove my items then ? Because when i do array[4] = null, my for just doesn't care and goes on trying to use the value at 4.
I also tried to check if !null but without success... thank you
Share Improve this question asked Dec 12, 2012 at 20:09 RayjaxRayjax 7,78413 gold badges57 silver badges85 bronze badges 3-
for in
's are for enumerating object properties. You should be using a standardfor
loop for iterating over an array. For more info see stackoverflow./questions/5263847/… – Matt Commented Dec 12, 2012 at 20:11 -
2
If you really need to iterate over a sparse array, use
for(i in array) { if(!isNaN(+i)) ... }
. (Bonus tip: you probably don't need to iterate over a sparse array. This is only for cases in which you have a array with hugely distant indices, e.g.5
and10000000
are the only populated indices.) – apsillers Commented Dec 12, 2012 at 20:13 - Delete the array element properly: stackoverflow./questions/500606/…. – Felix Kling Commented Dec 12, 2012 at 20:39
1 Answer
Reset to default 6If you want to remove an item without leaving a hole, you should use .splice()
myarray.splice(idx, 1);
But if you're saying that you want the holes there, but want to skip them, then you can use delete
to remove the item (leaving a hole), and use .forEach()
for the iteration, which skips holes.
delete myarray[idx];
// ...
myarray.forEach(function(item, i) {
// holes will be skipped
});
To support older browsers like IE8 and lower, you'll need to add a patibility patch for forEach()
.
- MDN
.forEach()
(Ignore the shorter patch. It's a poor non-pliant version.)