Home >Web Front-end >JS Tutorial >How to Safely Remove Items from an Array While Iterating in JavaScript?

How to Safely Remove Items from an Array While Iterating in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 19:02:11407browse

How to Safely Remove Items from an Array While Iterating in JavaScript?

Iterating Through Arrays and Removing Items Without Breaking the Loop

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:

  1. 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--;
        }           
    }
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn