Skip to content

手写深拷贝,注意 Object.assign 不是深拷贝

深拷贝函数

js
function deepClone(obj = {}) {
  // 一般拷贝的是对象或者数组
  if (typeof obj !== 'object' || typeof obj !== 'array') {
    return obj;
  }
  let res;
  if (typeof obj === 'array') {
    res = [];
  } else if (typeof obj === 'object') {
    res = {};
  }
  for (let key in obj) {
    // 判断是否属于自己的属性,不是原型的
    if (obj.hasOwnProperty(key)) {
      res[key] = deepClone(obj[key]);
    }
  }
  return res;
}
const obj1 = {
  a: 1,
  b: 2,
  c: {
    x: 10,
    y: {
      z: 20,
    },
  },
};
console.log(deepClone(obj1));
// {a: 1, b: 2, c: {…}}
// a: 1
// b: 2
// c:
// x: 10
// y:
// z: 20
// __proto__: Object
// __proto__: Object
// __proto__: Object

测试 Object.assign 不是深拷贝

js
const obj1 = {
  a: 1,
  b: 2,
  c: {
    x: 10,
    y: {
      z: 20,
    },
  },
};
const obj2 = Object.assign({}, obj1);
obj1.c.x = 30;
console.log(obj2.c.x); // 30

基于 MIT 许可发布