Skip to content

深拷贝和浅拷贝

深:因为 js 对象是引用类型,在对象赋值过程中,赋值的是地址,会导致原对象属性修改时,被赋值的那一方也发生修改,为了解决这个问题,我们使用深拷贝。

浅:只复制第一层,嵌套对象仍是引用;修改嵌套对象会互相影响。

js
let tag = { name: "tag" };
object.assign(tag, { name: "new", type: "assign" });
js
const a = {
  name: "a",
  child: {
    name: "child",
  },
  target: [1, 2],
};
a.target = a;

const deepClone = (value, cache = new WeakMap()) => {
  if (!value) return value;
  if (typeof value !== "object") return value;

  if (cache.get(value)) return cache.get(value);

  let result = new value.constructor();

  cache.set(value, result);

  Object.keys(value).map((item) => {
    result[item] = deepClone(value[item], cache);
  });
  return result;
};
const obj = deepClone(a);
a.name = "aa";

console.log(obj);
console.log(obj.name);

在 MIT 许可下发布