浅拷贝
方法一
function shallowClone(obj1, obj2) {
let obj = obj2 || {}
for (let i in obj1) {
obj[i] = obj1[i];
}
return obj;
}
let obj = { a: {b: "hello", c: 21} };
let obj2 = shallowClone(obj,{d:33});
obj.a.b = 'world';
console.log(obj2);
复制代码
方法二
let obj = { a: {b: "hello", c: 21} };
let obj2 = Object.assign({}, obj);
obj.a.b = 'world'
console.log(obj2);
复制代码
深拷贝
方法一
function deepClone(initalObj, finalObj) {
let obj = finalObj || {}
for (let i in initalObj) {
let prop = initalObj[i];
if (prop == obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === Array)?[]:{};
deepClone(prop, obj[i]);
} else {
obj[i] = prop;
}
}
return obj;
}
let obj = { a: {b: "hello", c: 21} };
let obj2 = deepClone(obj,{d:33});
obj.a.b = 'world';
console.log(obj2);
复制代码
方法二
let obj = { a: {b: "hello", c: 21} };
let obj2 = JSON.parse(JSON.stringify(obj));
obj.a.b = 'world';
console.log(obj2);
复制代码