1 使用JSON方法暴力解决

const obj = {name:’123’}
const obj2 = JSON.parse(JSON.springfy())

2 使用解构函数赋值

只能深拷贝一层 如下
const obj = { name:’456789’ };
const obj2={ …obj };
多层无法深拷贝
const obj3 = { name:’456789’, arr:[1,2,3] };
const obj4={ …obj3 };
obj4.arr.push(5,6)
console.log(obj3.arr)
console.log(obj4.arr)
打印结果都一样: [1, 2, 3, 5, 6]

3 使用对象合并进行

只能深拷贝一层 如下
const obj = {name:’123’,age:13};
const obj2 = Object.assign({},obj1);
多层无法深拷贝
const obj3 = { name:’456789’, arr:[1,2,3] };
const obj4={ …obj3 };
obj4.arr.push(5,6)
console.log(obj3.arr)
console.log(obj4.arr)
打印结果都一样: [1, 2, 3, 5, 6]

4 利用循环和递归的方法

function deepClone(obj, newObj){
const newObj = new Object() || {};
for (let key in obj) {
if (typeof obj[key] == ‘object’) {
newObj[key] = (obj[key].constructor === Array) ? [] : {} deepClone(obj[key], newObj[key]);
} else {
newObj[key] = obj[key]
}
}
return newObj;
}