一、一句话区别
- 浅拷贝:只复制第一层属性,嵌套对象仍共享引用。
- 深拷贝:递归复制所有层级,完全独立,互不影响。
二、浅拷贝 2 行代码
const shallow = { ...obj }; // 对象
const arrShallow = [...arr]; // 数组
三、深拷贝 3 种实现
① JSON 法(简单但有坑)
const deep = JSON.parse(JSON.stringify(obj));
// 坑:无法处理函数、undefined、循环引用、Date、RegExp
② 递归法(通用)
function deepClone(target) {
if (target === null || typeof target !== 'object') return target;
const clone = Array.isArray(target) ? [] : {};
for (let key in target) {
if (target.hasOwnProperty(key)) {
clone[key] = deepClone(target[key]);
}
}
return clone;
}
③ 现代法(结构化克隆)
const deep = structuredClone(obj); // 浏览器原生,支持循环引用
四、面试 10 秒回答模板
“浅拷贝只复制第一层,深拷贝递归复制所有层级;推荐
structuredClone
或手写递归。”