Solving the problem of removing elements when traversing an array and less traversing some elements

1. Forward traversal requires i-- to change the subscript (ps: note that the for.. in method cannot control traversal, i-- is invalid)

for (let i = 0; i < arr.length; i++) {

  if (arr[i] === 5) {

    arr.splice(i, 1); // Will move the following elements forward in sequence and reduce the array length by 1

    i--; // If not subtracted, one element will be missed.

  }

}

2. Flashback traversal. No matter how many elements are deleted during flashback traversal, the elements that have not been traversed will not be skipped.

for (let i = arr.length - 1; i >= 0; i--) {

        if (arr[i]  === 5) { arr.splice(i, 1); }

}

3. Filter out a new array and reassign the value

arr = arr.filter(item => item !== 5);

Guess you like

Origin blog.csdn.net/qq_42152032/article/details/130851876