javascript remove element in loop of array

In the process of developing JavaScript applications, we often encounter the need to remove specified elements in a loop.

According to the conventional idea, it is to perform a for loop on the array, and then perform an if judgment in the loop, and delete the specified element in the judgment.

But things often don't work out as smoothly as expected.

Problem scene restoration

( function () {
     var arr = [1, 2, 2, 3, 4, 5 ];
     for ( var i = 0; i < arr.length; i++ ){
         // Print the situation in the array, easy to track the array Data changes 
        console.log(i + ' = ' + arr[i]);
         // Remove all elements of 2 
        if (arr[i] === 2 ) {
            arr.splice(i, 1);
        }
    }
    console.log(arr);
})();

As can be seen from the final result, this code actually only deletes one of the matching elements, while another element matching the condition still exists, which is not in line with the original intention of the program design.

It is not difficult to find from the printed running process that the reason for this result is that when an element is deleted, the index (subscript) of the element in the array changes in real time, resulting in an exception to the program.

way of solving the problem

Once the cause of the problem is found, it is not difficult to solve the problem.

Method 1: Adjust the subscript correspondence of elements in the array in real time.

( function () {
     var arr = [1, 2, 2, 3, 4, 5 ];
     for ( var i = 0; i < arr.length; i++ ){
         // Print the situation in the array, easy to track the array Data changes 
        console.log(i + ' = ' + arr[i]);
         // Remove all elements of 2 
        if (arr[i] === 2 ) {
            arr.splice(i--, 1);
        }
    }
    console.log(arr);
})();

The reason for the problem is that after removing an element in the middle, the indices (subscripts) of the elements following the element are all incremented by 1, so we can manually reset the subscripts in the loop after deleting the elements It can be the corresponding subscript now (i--).

Method 2: Traverse the array elements from back to front.

( function () {
     var arr = [1, 2, 2, 3, 4, 5 ];
     for ( var i = arr.length - 1; i >= 0; i-- ) {
         // print the case in the array , easy to track the changes in the data in the array 
        console.log(i + ' = ' + arr[i]);
         // Remove all 2 elements 
        if (arr[i] === 2 ) {
            arr.splice(i, 1);
        }
    }
    console.log(arr);
})();

The reason for the problem is that after removing an element in the middle, the indices (subscripts) of the elements behind the element are all increased by 1, so as long as the loop is from back to front, you can ignore the elements behind it. index (subscript) too.

Method 3: Use a while loop instead of a for loop (or loop back to front).

(function () {
    var arr = [1, 2, 2, 3, 4, 5];
    var i = arr.length;
    while(i--) {
        console.log(i + ' = ' + arr[i]);
        if(arr[i] === 2) {
            arr.splice(i, 1);
        }
     }
    console.log(arr);
})();

It is the same as the principle of looping from back to front above, but the for loop is replaced by a while loop.

 

"Tomorrow's today is yesterday, and yesterday is a new day."

Reprinted in: https://www.cnblogs.com/yanggb/p/11596430.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324796819&siteId=291194637