赞
踩
一. 浅拷贝
let arr=[1,2,3,4]
let getData=arr;
getData.splice(0,1);//当强制删除其中某一个值时arr也被删除了
console.log(arr);//[2,3,4]
console.log(getData);//[2,3,4]
//问题:修改getData数组时,arr的数组不发生变化
let getData=Object.assign([],arr);
getData.splice(0,1)
console.log(arr);//[1,2,3,4]
console.log(getData);//[2,3,4]
二.深拷贝当一个数组中的对象发生变化时,则被建立引用关系接收的值也会发生变化
- //当一个数组中的对象发生变化时,则被建立引用关系接收的值也会发生变化
- handlePClickBefore(valOut){
- console.log('传进来的下标');
- console.log(valOut.sortId);
- //获取上一级的下标的内容,preLevel接收此对象的值建立了引用关系,
- 当所引用的对象this.controllerZyCount发生变化时
- preLevel也会发生变化
- let preLevel= this.controllerZyCount[valOut.sortId-1-1];
- //获取当前的下标的内容
- let getObject=this.controllerZyCount[valOut.sortId-1];
- this.controllerZyCount.splice(valOut.sortId-1,1, preLevel );
- this.controllerZyCount.splice(valOut.sortId-1-1,1,getObject);
- console.log('插入后');
- console.log(this.controllerZyCount);
- console.log(getObject['zyName']);
- //此时preLevel的值是正常的
- console.log( preLevel ['zyName']);
- console.log(this.controllerZyCount[valOut.sortId - 1]['zyName']);
- console.log(this.controllerZyCount[valOut.sortId - 1 - 1]['zyName']);
- this.controllerZyCount[valOut.sortId-1]['zyName']=getObject['zyName'];
- this.controllerZyCount[valOut.sortId-1]['sortId']=getObject['sortId'];
- //等到修改controllerZyCount[valOut.sortId-1]中的值时,preLevel发生了变化
- console.log( preLevel ['zyName']);
- this.controllerZyCount[valOut.sortId-1-1]['zyName']=preLevel.zyName;
- this.controllerZyCount[valOut.sortId-1-1]['sortId']= preLevel.sortId;
-
- },
2.解决以上问题的方式用深拷贝解决
- //上移
- handlePClickBefore(valOut){
- console.log('传进来的下标');
- console.log(valOut.sortId);
- //获取上一级的下标的内容
- let preLevel= JSON.stringify(this.controllerZyCount[valOut.sortId-1-1]);
- // let preLevelSortId=this.controllerZyCount[valOut.sortId-1-1]['sortId'];
- // let preLevelZyName=this.controllerZyCount[valOut.sortId-1-1]['zyName'];
- //获取当前的下标的内容
- let getObject=this.controllerZyCount[valOut.sortId-1];
- this.controllerZyCount.splice(valOut.sortId-1,1,JSON.parse(preLevel));
- this.controllerZyCount.splice(valOut.sortId-1-1,1,getObject);
- console.log('插入后');
- console.log(this.controllerZyCount);
- console.log(getObject['zyName']);
- console.log(JSON.parse(preLevel)['zyName']);
- console.log(this.controllerZyCount[valOut.sortId - 1]['zyName']);
- console.log(this.controllerZyCount[valOut.sortId - 1 - 1]['zyName']);
- this.controllerZyCount[valOut.sortId-1]['zyName']=getObject['zyName'];
- this.controllerZyCount[valOut.sortId-1]['sortId']=getObject['sortId'];
- console.log(JSON.parse(preLevel)['zyName']);
-
- this.controllerZyCount[valOut.sortId-1-1]['zyName']=JSON.parse(preLevel).zyName;
- this.controllerZyCount[valOut.sortId-1-1]['sortId']=JSON.parse(preLevel).sortId;
- this.$set(this.controllerZyCount);
- console.log('赋值后');
- console.log(this.controllerZyCount);
- },
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。