function deepClone(val) {
const type = getType(val);
// 如果不是数组或对象,不需要递归,则直接返回
if (type !== 'Array' && type !== 'Object') {
return val;
}
// 如果是数组或对象,构造一个新的,遍历复制
let res = type === 'Object' ? {} : [];
for (let key in val) {
const subVal = val[key];
const subType = getType(subVal);
if (subType !== 'Object' && subType !== 'Array') {
res[key] = subVal;
} else {
res[key] = deepClone(subVal);
}
}
return res;
// 获取类型工具函数
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1);
}
}
// const arr1 = [1, 2, 3, 4, 5]
// const arr2 = deepClone([1, 2, 3, 4, 5])
// arr1[1] = 10
// console.log(arr1, arr2)
const obj1 = { a: 1, b: 2, c: 3, d: 4, e: { a: 1, b: 2, c: 3 } }
const obj2 = deepClone(obj1)
obj1.e.a = 1000
console.log(obj1, obj2)
参考
https://www.cxymsg.com/guide/jsWritten.html#%E5%AE%9E%E7%8E%B0%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0%EF%BC%88debounce%EF%BC%89
https://www.yuque.com/chenyubo/knowledge-map/qus818#OP8CP