描述
- 当obj对象拷贝到obj2对象是childs参数不会重新创建新的对象,而是生成obj2.childs的指针,指向obj.childs栈(引用类型的值),当obj.childs更改是obj.childs的属性也会随之改变
var obj = {
name:'zs',
childs:{
name:'ls'
}
}
递归赋值对象(深拷贝)
var obj1 = {
name:'zs',
age:18,
childs:{
dog:'jm',
age:2
},
arr:[1,2,3,4,5,6,7]
}
var obj2 = {}
function deepCopy(obj1,obj2){
for(var key in obj1){
var tiem = obj1[key];
if(tiem instanceof Array){
obj2[key] = {}
deepCopy(tiem,obj2[key])
}else if(tiem instanceof Object){
obj2[key] = [];
deepCopy(tiem,obj2[key])
}else{
obj2[key] = obj1[key]
}
}
}
deepCopy(obj1,obj2);
obj1.childs.age = 18
console.log(obj1) //18
console.log(obj2) //2
利用JSON实现深拷贝
let obj = {
name:"测试"
}
let copyObj = JSON.stringify(obj)
let copyDeepObj = JSON.parse(copyObj)