-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeep-clone.js
39 lines (35 loc) · 1.08 KB
/
deep-clone.js
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
function deepClone(obj, cache = new WeakMap()) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
// const hit = cache.find(v => v.original === obj);
const hit = cache.get(obj);
if (hit) {
// return hit.copy;
return hit;
}
const copy = Array.isArray(obj) ? [] : {};
// cache 处理循环引用的情况
// cache.push({
// original: obj,
// copy
// });
cache.set(obj, copy);
// ownKeys = Object.getOwnPropertyNames (包括不可枚举属性) (而 Object.keys 返回的是自身可枚举属性(除 Symbol 外)组成的数组,“可枚举”即“可遍历”) + Object.getOwnPropertySymbols
// for...in语句以任意顺序遍历一个对象的除 Symbol 以外的可枚举属性。
Reflect.ownKeys(obj).forEach((key) => {
copy[key] = deepClone(obj[key], cache);
});
return copy;
}
const test = {
a: [1, 2, Symbol('123')],
b: {
c: 45,
d: Symbol('abc'),
},
aa: null,
};
test.f = test;
const newTest = deepClone(test);
console.log(newTest);