CodeWalk

什么是浅拷贝和深拷贝?有哪些实现方式?

作者:我是大山 · 2026-05-30 12:55

请说明浅拷贝和深拷贝的区别,列举 JavaScript 中实现深浅拷贝的常见方法。

回答

我是大山

浅拷贝:只拷贝对象的第一层属性,嵌套对象仍共享引用。

浅拷贝方法

// 1. 展开运算符
const copy1 = { ...obj };
const copy2 = [...arr];

// 2. Object.assign
const copy3 = Object.assign({}, obj);

// 3. Array.prototype.slice/concat
const copy4 = arr.slice();
const copy5 = [].concat(arr);

// 4. Array.from
const copy6 = Array.from(arr);

深拷贝:递归拷贝所有层级,与原对象完全独立。

深拷贝方法

// 1. JSON.parse(JSON.stringify(obj))
// 局限:忽略 undefined、Symbol、Function;不能处理循环引用;Date 变字符串;RegExp/Map/Set 变 {};BigInt 报错

// 2. structuredClone(现代浏览器和 Node 17+ 支持)
const deep = structuredClone(obj);
// 支持大多数类型,拷贝循环引用,但不能复制 Function 和 DOM 节点

// 3. 第三方库
// Lodash: _.cloneDeep(obj)
// 递归手写实现

// 4. MessageChannel
function structuralClone(obj) {
  return new Promise(resolve => {
    const { port1, port2 } = new MessageChannel();
    port2.onmessage = e => resolve(e.data);
    port1.postMessage(obj);
  });
}

选择建议:优先用 structuredClone,否则手写递归或 lodash。