Looping through array and removing items, without breaking for loop

The array is being re-indexed when you do a .splice(), which means you’ll skip over an index when one is removed, and your cached .length is obsolete.

To fix it, you’d either need to decrement i after a .splice(), or simply iterate in reverse…

var i = Auction.auctions.length
while (i--) {
    if (...) { 
        Auction.auctions.splice(i, 1);

This way the re-indexing doesn’t affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.

Leave a Comment