1.实现浅拷贝

// 1. ...实现
let copy1 = {...{x:1}}

// 2. Object.assign实现

let copy2 = Object.assign({}, {x:1})

2. 实现深拷贝

// 1. JOSN.stringify()/JSON.parse()
let obj = {a: 1, b: {x: 3}}
JSON.parse(JSON.stringify(obj))

// 2. 递归拷贝
function deepClone(obj) {
  let copy = obj instanceof Array ? [] : {}
  for (let i in obj) {
    if (obj.hasOwnProperty(i)) {
      copy[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
    }
  }
  return copy
}

  

相关文章:

  • 2022-12-23
  • 2022-02-26
  • 2022-12-23
  • 2022-12-23
  • 2021-03-31
  • 2021-09-23
  • 2021-11-01
猜你喜欢
  • 2022-01-06
  • 2021-04-18
  • 2022-12-23
  • 2021-06-08
  • 2022-12-23
  • 2022-01-14
相关资源
相似解决方案