手寫深拷貝


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)
作用: 將所有可枚舉屬性的值從一個或多個源對象復(fù)制到目標對象。它將返回目標對象。

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容