3

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

Rayjax
  • 7,494
  • 11
  • 56
  • 82
  • `for in`'s are for enumerating object properties. You should be using a standard `for` loop for iterating over an array. For more info see http://stackoverflow.com/questions/5263847/javascript-loops-for-in-vs-for – Matt Dec 12 '12 at 20:11
  • 1
    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` and `10000000` are the only populated indices.) – apsillers Dec 12 '12 at 20:13
  • Delete the array element properly: http://stackoverflow.com/questions/500606/javascript-array-delete-elements. – Felix Kling Dec 12 '12 at 20:39

1 Answers1

6

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.)
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77