I have the following for loop, and when I use splice()
to remove an item, I then get that 'seconds' is undefined. I could check if it's undefined, but I feel there's probably a more elegant way to do this. The desire is to simply delete an item and keep on going.
for (i = 0, len = Auction.auctions.length; i < len; i++) {
auction = Auction.auctions[i];
Auction.auctions[i]['seconds'] --;
if (auction.seconds < 0) {
Auction.auctions.splice(i, 1);
}
}
Another simple solution to digest an array elements once:
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...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.
Recalculate the length each time through the loop instead of just at the outset, e.g.:
That way you won't exceed the bounds.
EDIT: added a decrement in the if statement.
Here is another example for the proper use of splice. This example is about to remove 'attribute' from 'array'.
If you are e using ES6+ - why not just use Array.filter method?
Note that modifying the array element during filter iteration only works for objects and will not work for array of primitive values.