1. 程式人生 > >手動實現深拷貝

手動實現深拷貝

手動實現深拷貝的三種方法:

// 方法一
Object.prototype.deepClone = function () {
  let objClone = Array.isArray(this) ? [] : {}

  if (this && typeof this === 'object') {
    for (let key in this) {
      if (this.hasOwnProperty(key)) {
        if (this[key] && typeof this[key] === 'object') {
          objClone[key] = this[key].deepClone()
        } else {
          objClone[key] = this[key]
        }
      }
    }
  }

  return objClone
}

// 方法二
function deepClone(obj) {
  let objClone = Array.isArray(obj) ? [] : {}

  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClone(obj[key])
        } else {
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
 }
// 方法三
function deepClone(obj) {
  if (obj && typeof obj === 'object') {
    let objString = JSON.stringify(obj)
    return JSON.parse(objString)
  }
}

var a = {
  a: 1,
  b: 2,
  c: [1, 2, 3]
}

let b = deepClone(a)

a.c[0] = 4

console.log(a, b)