实现深拷贝是为了两个对象内存互不干扰。
这里解决了我们常用的JSON深拷贝带来的问题;
核心:判断传入的obj的类型,为数组的话返回处理后的数组,数组的每一项都进行递归,为函数的话返回obj,为对象的话,将key和value分别加入到两个数组,添加到temp这个对象,添加的同时递归当前value,其他直接返回。
const deepClone = (obj) => {
if (obj instanceof Array) {
return obj.map(item => deepClone(item))
} else if (obj instanceof Function) {
return obj
}else if (obj instanceof Object) {
let temp = {}
let keys = Object.keys(obj)
let values = Object.values(obj)
keys.forEach((item, index) => {
temp[item] = deepClone(values[index])
})
return temp
}
else {
return obj
}
}
测试:
let obj = {
key: '123',
name: "zjq",
list: [1, 2, 3, 4, { zjq: "zjq" }, 6, 7, { fyy: { fyy: 'fyy' } }, [1, 2, 3, { name: "zjq" }]],
smallObj: {
habby: {
one: "running",
two: "switing"
}
}
}
let list = [1, 2, 3, 4, { zjq: "zjq" }, 6, 7, { fyy: { fyy: 'fyy' } }, [1, 2, 3, { name: "zjq" }]];
//测试对象深拷贝
console.log(" deepClone(666)", deepClone(666))
let zjq = deepClone(obj)
zjq.list[7].fyy.fyy = "99999"
zjq.list[8][3].fyy = "99999"
console.log(" deepClone({key:'123'})", zjq)
obj.smallObj.habby = "1233333"
obj.list[4].zjq = "1233333"
obj.list[7].fyy.fyy = "1233333"
console.log(obj);
console.log("======================================================");
//测试数组深拷贝
let listA = deepClone(list)
list[4].zjq = 0000
list[7].fyy = 111
listA[7].fyy.fyy = 8888
console.log(list);
console.log(listA);