深拷贝和浅拷贝代码实现

/**

 * 深拷贝

 */

const obj1 = {

  age: 18,

  name: "xxx",

  address: {

    city: "beijing"

  },

  arr: ['a', 'b', 'c']

}

const obj2 = deepClone(obj1);

console.log(obj2);

obj2.address.city = '上海';

console.log(obj1.address.city);

function deepClone(obj = {}) {

  if (typeof obj !== 'object' || obj == null) {

    // obj 是null 或者不是数组或者对象,直接返回

    return obj

  }

  // 初始化返回结果

  let result;

  if (obj instanceof Array) {

    result = []

  } else {

    result = []

  }

  for (let key in obj) {

    // 保证key不是原型链的属性

    if (obj.hasOwnProperty(key)) {

      // 递归调用

      result[key] = deepClone(obj[key])

    }

  }

  // 返回结果

  return result

}


// 浅拷贝

// const obj1 = {

//   age: 18,

//   name: "xxx",

//   address: {

//     city: "beijing"

//   },

//   arr: ['a', 'b', 'c']

// }

// const obj2 = obj1;

// obj2.address.city = '上海';

// console.log(obj1.address.city);

谢谢收看,欢迎关注分享留言哦!如有侵权问题请联系作者删除。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容