一、实现浅拷贝
直接赋值
let obj = { a: 1, b: { x: 2 }, arr: [1, [2], 3]};
let obj1 = obj
obj1.b.x = 20;
console.log(obj1);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
console.log(obj);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
Object.assign方法
let obj = { a: 1, b: { x: 2 }, arr: [1, [2], 3]};
let obj1 = Object.assign(obj);
obj1.b.x = 20;
console.log(obj1);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
console.log(obj);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
for···in循环
function lightCopy(obj) {
let copy = Array.isArray(obj) ? [] : {};
for (let i in obj) {
copy[i] = obj[i];
}
return copy;
}
let obj = { a: 1, b: { x: 2 }, arr: [1, [2], 3]};
let obj1 = lightCopy(obj);
obj1.b.x = 20;
console.log(obj1);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
console.log(obj);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
二、实现深拷贝
JSON.stringify方法
function deepCopy(obj) {
let copy = JSON.parse(JSON.stringify(obj))
return copy
}
let obj = { a: 1, b: { x: 2 }, arr: [1, [2], 3]};
let obj1 = deepCopy(obj);
obj1.b.x = 20;
console.log(obj1);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
console.log(obj);
// expected output: { a: 1, b: { x: 2 }, arr: [1, [2], 3]};
for···in循环加递归
function deepCopy(obj) {
let copy = obj instanceof Array ? [] : {};
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
copy[i] = typeof obj[i] === "object" ? deepCopy(obj[i]) : obj[i];
}
}
return copy;
}
let obj = { a: 1, b: { x: 2 }, arr: [1, [2], 3]};
let obj1 = deepCopy(obj);
obj1.b.x = 20;
console.log(obj1);
// expected output: { a: 1, b: { x: 20 }, arr: [1, [2], 3]};
console.log(obj);
// expected output: { a: 1, b: { x: 2 }, arr: [1, [2], 3]};