1. 浅拷贝:默认在改变新的数组的时候,也改变了原数组。
let obj = { name: "张三", age: 28 }; let qian = obj; qian.name = "李四"; console.log(obj.name); //李四 console.log(qian.name); //李四
2. 深拷贝:
方式一:使用JSON.stringify()以及JSON.parse():
let obj = { name: "张三", age: 28 }; let strObj=JSON.stringify(obj); let deep=JSON.parse(strObj); deep.name= "李四"; console.log(obj.name); //张三 console.log(deep.name); //李四
方式二;concat(数组):
let arr1=['张三','王五'] let arr2=[] let res=arr1.concat(arr2) res[0]= "李四"; console.log(arr1[0]); //张三 console.log(res[0]); //李四
方式三:通过for in实现:
//data let obj = { name: "张三", age: 28 }; //methods deepCopy(val) { let newObj = {}; for (let i in val) { newObj[i] = val[i]; } return newObj; }
方式四:递归:
//data let obj = { name: "张三", age: 28 }; //methods deepCopy(val) { //判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝 var newObj = Array.isArray(obj) ? [] : {}; //进行深拷贝的不能为空,并且是对象 if (val && typeof val === "object") { for (i in val) { if (val.hasOwnProperty(i)) { if (val[i] && typeof val[i] === "object") { newObj[i] = deepCopy(val[i]); } else { newObj[i] = val[i]; } } } } return newObj; }
标签:obj,name,val,16,newObj,let,拷贝 From: https://www.cnblogs.com/chenJieLing/p/17532280.html