js深拷贝
2026-09-07 12:00:01
function deepClone(obj, map = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (map.has(obj)) return map.get(obj); // 解决循环引用
const clone = Array.isArray(obj) ? [] : {};
map.set(obj, clone);
for (const key of Object.keys(obj)) {
clone[key] = deepClone(obj[key], map);
}
return clone;
}