Talking about js Array splice Deleting an Element Climbing Pit

  • 2021-08-31 06:57:35
  • OfStack

Let's look at the following concepts first:


// splice: Returns items deleted from the original array (an empty array if no deletions are made) 
    //  When you specify 2 Parameters, indicating the deletion of 
    //  When you specify 3 Parameters, and the first 2 Parameters are 0 Insert when 
    //  When you specify 3 Parameters, and the first 2 Parameters are 1 When means replacement 

Let's take deletion as an example. We want to delete a specified element in an array. We need to know the subscript in the array where it is located. We can use the array. indexOf to get its subscript, and then use splice to delete this element.

It's no problem in itself

The code is as follows:


var arr = [" Zhang 3"," Li 4"," Wang 5"," Zhao 6"];

//  Delete King 5
arr.splice(arr.indexOf(" Wang 5"),1);

But. . . . . Here comes the problem.

If we put it in an for loop, such as a circular array, we need to delete a specified element when a certain condition holds.

However, in the loop, i is +1 every time, but after we delete an element, the subscript changes and the corresponding position changes. After adding 1 to the value of i, the next element will be skipped.

Pit. . .

Therefore, when deleting an element, we manually subtract the value of i by another 1, which will avoid the problem of skipping an element.

For example, a circular array, when the DasOperation property value is equal to unchanged, delete this data from the array, and then i-1


//  Delete unchanged ones and do not pass them to the background 
for (let i = 0; i < this.CurrJobData.Content.length; i += 1) {
  if (this.CurrJobData.Content[i].DasOperation === ' No change ') {
    this.CurrJobData.Content.splice(this.CurrJobData.Content.indexOf(this.CurrJobData.Content[i]), 1);
    i -= 1;//  Must be right i Subtract 1 Otherwise, the following 1 Elements will be skipped 
  }
}

Ok, in order to avoid more friends encountering pits, post it, hoping it will help.


Related articles: