javascript 深拷贝

javascript 深拷贝

const obj1 = {
  name: 'xxx',
  age: 18,
  address: {
    city: '北京'
  },
  arr: [1, 2, 3],
  add: () => {console.log(1)}
}

function deepClone(obj = {}) {
  if(typeof obj !== 'object' || obj == null) {
    //如果obj 不等于对象或者数组或者obj等于null 直接返回
    return obj
  }
  //返回数据
  let result
  if(obj instanceof Array) {
    result = []
  }else {
    result = {}
  }
  //遍历对象
  for(let key in obj) {
    if(obj.hasOwnProperty(key)) {
      //递归
      result[key] = deepClone(obj[key])
    }
  }
  //返回
  return result
}   

const obj2 = deepClone(obj1)
obj2.address.city = "上海"
console.log(obj1.address.city) //北京

还有一种简单粗暴的方法:JSON.stringify()和JSON.parse() 【但是这种方法存在缺陷】

const obj1 = {
  name: 'xxx',
  age: 18,
  address: {
    city: '北京'
  },
  arr: [1, 2, 3],
  add: () => {console.log(1)}
}

const obj1Str = JSON.stringify(obj1)
const obj2 = JSON.parse(obj1Str)
console.log(obj2)

缺陷:

js方法拷贝不上!!!!!!!!!!!
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值