手写深拷贝

2022-03-28  本文已影响0人  bryan_liu
function deepClone(obj = {},map = new Map()) {
  if(typeof obj !== 'object') {
    return obj
  }
  if(map.get(obj)) {
    return map.get(obj)
  }
  // 初始化返回结果
  let result = {}
  if(obj instanceof Array || Object.prototype.toString(obj) === "[object Array]") {
    result = []
  }
  // 防止循环引用
  map.set(obj,result)
  for(const key in obj){
    if(obj.hasOwnProperty(key)) {
      // 递归调用
      result[key] = deepClone(obj[key],map)
    }
  }
  // 返回结果
  return result
}
上一篇 下一篇

猜你喜欢

热点阅读