手动实现深克隆

本文最后更新于:2023年3月19日 晚上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function deepClone(obj, map = new WeakMap()) {
if (!obj instanceof Object) return obj;
if (map.has(obj)) return map.get(obj);
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (obj instanceof Function)
return function () {
obj.apply(this, arguments);
};
const res = Array.isArray(obj) ? [] : {};
map.set(obj, res);
const keys = Object.keys(obj).forEach((key) => {
if (obj[key] instanceof Object) {
res[key] = deepClone(obj[key]);
} else {
res[key] = obj[key];
}
});
return res;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!