问题
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
回答1:
If 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 compatibility patch for forEach()
.
- MDN .forEach() (Ignore the shorter patch. It's a poor non-compliant version.)
来源:https://stackoverflow.com/questions/13847769/iterating-over-an-array-with-holes-in-javascript