zoukankan      html  css  js  c++  java
  • javascript数组赋值操作的坑

    描述:数组对象赋值,即arr1=[{},{},{}]这种数据结构的对象赋值,将arr1赋值给arr2;然后删除arr2里的元素

    一、最常用的=

    arr2 = arr1;

    detect(val) {
          let temp = [];
          let self=this;
          temp = self.tableBaseStorage; //这个tableBaseStorage是data(){return{}}全局变量
          console.log("tableBaseStorage");
          console.log(self.tableBaseStorage);
          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);
          self.tableBase = temp;
          //console.log(this.tableBase);
        },

    你会发现当这个函数被第二次调用的时候,按理说this.tableBaseStorage是不会变的,每一次调用这个函数,都是从tableBaseStorage拿到数据那后对其筛选删除;

    但奇怪的是这个tableBaseStorage却是变了,第二次调用好像莫名其妙的被掉包了一样;

    现象:第一次调用detect()函数删了temp什么元素,tableBaseStorage同样被删除了同样的元素,故第二次再调用detect()函数此时的tableBaseStorage已经变了;

    原因:JavaScript中=赋值是指针赋值,删除中间变量temp[ ]里的元素,会一直删到它爹tableBaseStorage

    下面有几种解决措施供参考

    二、解决措施,避免数组的指针赋值

    1.循环赋值

        let temp = [];
          let self=this;
          for(let j=0;j<self.tableBaseStorage.length;j++){
             temp[j] = self.tableBaseStorage[j];
          }

    2.数组的concat方法

    说明

    返回一个新数组,这个新数组是由两个或更多数组组合而成的。

    array1.concat([item1[, item2[, . . . [, itemN]]]])

    参数

    array1

    必选项。其他所有数组要进行连接的 Array 对象。

    item1,. . ., itemN

    可选项。要连接到 array1 末尾的其他项目。

    示例

    //temp=self.tableBaseStorage.concat();

    3.JSON.parse & JSON.stringify

    先stringify再parse成数组对象

    temp = JSON.parse(JSON.stringify(self.tableBaseStorage))

    4.es6提供的一种方法

    //temp = [...self.tableBaseStorage];
  • 相关阅读:
    tomcat项目部署后,无法弹出浏览器窗口,IDEA控制台如何快速找到错误日志
    导入新的jar包后,提示ClassNotFoundException 怎么解决?
    Vue is not defined
    next(),nextLine(),nextInt的区别
    Properties类与流的相关方法,properties的键与值都应该是字符串
    Java并发编程从入门到精通
    Java并发编程从入门到精通
    Java并发编程从入门到精通
    Java并发编程从入门到精通
    Java并发编程从入门到精通
  • 原文地址:https://www.cnblogs.com/yanl55555/p/12000560.html
Copyright © 2011-2022 走看看