-
深拷贝
在计算机中开辟一块新的内存地址用于存放复制的对象
let obj1 = {
name:'jack',
age:15,
arr:[1,2,3],
};
let obj2 = {};
deepCopy(obj1,obj2);
console.log(obj1);
console.log(obj2);
obj1.age = 20;
console.log(obj1);
console.log(obj2);
function deepCopy(obj1,obj2) {
for(let i in obj1){
if(obj1[i].constructor === Array){
obj2[i]=[];
obj2[i] = obj1[i];
}else{
obj2[i]={};
obj2[i] = obj1[i];
}
}
}
运行结果:
-
浅拷贝
只是增加了一个指针指向已存在的内存地址
let oldObj = { a:1, arr: [2,3] };
let shallowObj = oldObj;
console.log(oldObj);
console.log(shallowObj);
oldObj.a = 5;
console.log(oldObj);
console.log(shallowObj);
运行结果