关于javascript:JavaScript深拷贝

8次阅读

共计 426 个字符,预计需要花费 2 分钟才能阅读完成。

const oldObj = {
  name: 'tao',
  age: 20,
  color: ['orange', 'green', 'blue'],
  friend: {name: 'gua'},
  fn: function(){console.log(1)
  }
}
function deepClone(obj) {
  // 判断不是数组或对象
  if(typeof obj !== 'object' || obj === null) {return obj}
  let res
  if(obj instanceof Array) {res = []
  } else {res = {}
  }
  for(let k in obj) {
    // 过滤掉 obj 原型上的属性
    if(obj.hasOwnProperty(k)) {res[k] = deepClone(obj[k])
    }
  }
  return res
}
const newObj = deepClone(oldObj)
newObj.friend.name = 'taotao'
console.log(oldObj, newObj)
newObj.fn()
正文完
 0