首先,简单赋值:
const obj1 = {
age: 22,
name: 'xxx',
address: {
city: 'beijing',
},
arr: [1,2,3,4],
}
const obj2 = obj1;
obj2.arr[0] = 11;
console.log(obj1);
结果展示:
深拷贝的实现:
const obj1 = {
age: 22,
name: 'xxx',
address: {
city: 'beijing',
},
arr: [1,2,3,4],
}
// const obj2 = obj1;
// obj2.arr[0] = 11;
// console.log(obj1);
const obj3 = deepClone(obj1);
obj3.address.city = 'shanghai';
console.log(obj1);
/**
* 深拷贝
*/
function deepClone(obj) {
if (typeof obj !== 'object' || obj == null) {
// 如果是null,或者不是object,就直接返回
return obj;
}
// 初始化返回结果
let result;
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
// 保证 key 不是原型的属性
if (obj.hasOwnProperty(key)) {
// 递归
result[key] = deepClone(obj[key]);
}
}
// 返回结果
return result;
}