浅拷贝只复制对象第一层,嵌套的数组或对象仍然是引用,修改副本的内层会污染原对象;深拷贝递归复制所有层级,两个对象完全独立。浅拷贝的常见实现是 Object.assign、展开运算符和数组的 slice;深拷贝最简单的是 JSON 序列化再反序列化,但会丢失函数、undefined、Symbol 和循环引用。
面试要求手写深拷贝时,标准答案是用递归加 WeakMap 解决循环引用,对 Date、RegExp、Map、Set 等特殊类型分别处理,数组用 Array.isArray 初始化容器。回答时要主动对比 JSON 方案的缺陷,再讲原生 structuredClone 等更完善的方案。
// 深拷贝:递归 + WeakMap 处理循环引用 function deepClone(source, cache = new WeakMap()) { if (source === null || typeof source !== 'object') return source; if (cache.has(source)) return cache.get(source); const target = Array.isArray(source) ? [] : {}; cache.set(source, target); Reflect.ownKeys(source).forEach(key => { const val = source[key]; target[key] = (val !== null && typeof val === 'object') ? deepClone(val, cache) : val; }); return target; } const a = { n: 1, list: [2, 3], self: null }; a.self = a; // 循环引用 const b = deepClone(a); console.log(b.list, b.self === b, b.list === a.list); // [2,3] true false