In javascript array element deletion method splice, with a giant pit in a for loop

One, demo

splice: The method will automatically change the length of the original array

Example:

 var Array = [ "AA", "dd", "CC", "AA" ];
    // Method 2: Remove array elements 
    Array.splice (1,1 );
    // Output Results: [ "aa", "cc "," AA "] 
   getArray (Array);

Output: aa 

   cc

   aa

Automatic array length minus one

 

Second, the actual business scenarios

In the loop for manipulation by y temp.splice (i, 1);

Be sure to remember to follow written i--

detect() {
      let temp = [];
      temp = this.tableBase;
      let userName = this.search;
      let count = 0;
      for (let i = 0; i < temp.length; i++) {
        if (!(temp[i].userName === userName)) {
          console.log(temp[i].userName);
          temp.splice (i, 1); // delete this manner will automatically update length, caution
          i--;
          //delete temp[i];
          count++;
          console.log ( "delete");
        }
      }
      console.log(count);
      this.tableBase = temp;
      console.log(this.tableBase);
    },

 

Guess you like

Origin www.cnblogs.com/yanl55555/p/11997617.html