zoukankan      html  css  js  c++  java
  • javascript中数组元素删除方法splice,用在for循环中巨坑

    一、demo

    splice: 该方法会改变自动原始数组长度

    实例:

     var array = ["aa","dd","cc","aa"];
       //方法2:删除数组元素
        array.splice(1,1);
       //输出结果:["aa","cc","aa"]
       getArray(array);

    输出:aa 

       cc

       aa

    数组长度自动减一

    二、实际业务场景中

    在for循环中使y用 temp.splice(i, 1);

    一定要记得跟着写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); //这种删除方式会自动更新长度,慎用
              i--;
              //delete temp[i];
              count++;
              console.log("删除");
            }
          }
          console.log(count);
          this.tableBase = temp;
          console.log(this.tableBase);
        },
  • 相关阅读:
    CodeForces 687B Remainders Game
    CodeForces 689D Friends and Subsequences
    CSU 1810 Reverse
    生成树收录
    吃奶酪
    带逆向思维的并查集
    中位数定理
    种类并查集(关押犯人)
    带权并查集
    分层图
  • 原文地址:https://www.cnblogs.com/yanl55555/p/11997617.html
Copyright © 2011-2022 走看看