手写深拷贝

2020-08-01  本文已影响0人  泡杯感冒灵

function deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  let res 

  if (obj instanceof Array) {
    res = []
  } else {
    res = {}
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      res[key] = deepClone(obj[key])
    }
  }

  return res
}

注意:Object.assign()不是深拷贝

语法:Object.assign(target, ...sources)
作用: 将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

const target = { a: 1, b: 2 }
const source = { b: 3, c: 4 }

const returnedTarget = Object.assign(target, source)

console.log(target)  // {a: 1, b: 3, c: 4}
console.log(returnedTarget)  // {a: 1, b: 3, c: 4}

// 给 returnedTarget 追加一个属性
const returnedTarget2 = Object.assign(returnedTarget, { d: 5 })
console.log(returnedTarget2)  // {a: 1, b: 3, c: 4, d: 5}

看似是深拷贝

const souce = { b: 3, c: 4 }
const deepSource = Object.assign({}, source)
console.log(deepSource)  // {b: 3, c: 4}
source.b = 10
console.log(deepSource.b)  // 3

但其实是拷贝的source的第一层级(c:4,d:5),如果source还有第二层级(d:{...}),就看出不是深拷贝了

const source = { b: 3, c: 4, d: {x:5,y:6}}

const deepObj = Object.assign({}, source)
console.log(deepObj)  
console.log(deepObj.d.x)  // 5
source.d.x = 7
console.log(deepObj.d.x)  // 7
上一篇下一篇

猜你喜欢

热点阅读