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);
        },
  • 相关阅读:
    MySQL性能调优——索引详解与索引的优化
    Linux命令之文件搜索
    MySQL中的行级锁,表级锁,页级锁
    MySQL存储引擎
    Linux软链接和硬链接
    linux学习笔记
    在浏览器中输入一个网址后,发生了什么?
    二叉排序树
    有序表查找
    为view设置虚线边框
  • 原文地址:https://www.cnblogs.com/yanl55555/p/11997617.html
Copyright © 2011-2022 走看看