深拷贝
2019-11-21 本文已影响0人
Joah_l
/**
* NOTE: 深拷贝
*/
function deepCopy(target) {
// NOTE: 过滤掉基础类型
if (typeof target !== 'object') {
return target
}
let n;
// NOTE: 处理引用类型
if (Array.isArray(target)) {
n = new Array(target.length);
target.forEach((v, i) => (n[i] = deepCopy(v)));
} else {
n = {}
Object.keys(target).forEach(key => {
n[key] = deepCopy(target[key]);
});
}
return n
}
const a = {
a: [
1,
[4],
{
a: {
c: [4]
}
}
],
c: () => {
console.log(1)
}
}
const b = deepCopy(a);
a.c = "c";
console.log(a);
console.log(b);
console.log(a.c);
console.log(b.c)