实现深拷贝

实现一个深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const obj = {
name: "aaa",
age: 18,
friend: ["bbb", "ccc", "ddd"],
bar: {
count: 1,
foo: {
msg: "hello world",
},
},
add(n1, n2) {
return n1 + n2;
},
};
obj.self = obj;

// 判断是否为对象类型
function isObject(obj) {
return typeof obj === "object" && obj !== null;
}

// WeakMap为弱引用,map和target为弱引用关系,若后续将target = null 则这块内存会自动被清理
// Map为强引用,就算将target = null,因为Map还引用着obj,那么这块内存不会被清理
function deepCopy(target, map = new WeakMap()) {
// 不是对象直接返回
if (!isObject(target)) return target;

//是函数类型也直接返回
if (typeof target === "function") return target;

// 存在原对象则直接返回 解决循环引用
if (map.get(target)) return map.get(target);

// 如果是数组则创建数组类型,不是则创建对象类型
let newTarget = Array.isArray(target) ? [] : {};

// 储存新创建的对象
map.set(target, newTarget);

for (let key in target) {
// 递归遍历
newTarget[key] = deepCopy(target[key], map);
}

return newTarget;
}

const deepTaeget = deepCopy(obj);
console.log(deepTaeget);