Home >Web Front-end >JS Tutorial >How to Safely Remove Items from an Array While Iterating in JavaScript?
When removing items from an array within a loop, you may encounter an issue where splice() renders subsequent elements inaccessible. This is because splice() reindexes the array, potentially skipping items.
Problem:
In the following example, decrementing "seconds" and then splicing the item based on its negative value causes an undefined error:
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); } }
Solution:
To resolve this issue, consider two approaches:
Decrement Index After Splice(): After removing an item with splice(), decrement "i" to adjust for the reindexing:
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); i--; } }
Iterate in Reverse: Start the loop with the last index and iterate in reverse:
var i = Auction.auctions.length while (i--) { ... if (...) { Auction.auctions.splice(i, 1); } }
This way, the reindexing affects only subsequent elements, allowing for a continuous loop.
The above is the detailed content of How to Safely Remove Items from an Array While Iterating in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!