js实现深拷贝(考虑循环引用)

第一种

let obj = {
    name:"111",
    age:20,
    info:{
      hobby:['aa','bb',{
        a:1
      }],
      career:{
        teacher :111
      },
      style:{
        color:'red',
      }
    }
  }
  function deepClone(origin,target){
    let tag = target || {}
    for (const k in origin) {
      if(origin.hasOwnProperty(k)){
        if(typeof origin[k] === 'object' && origin[k] !== null){
          tag[k] = Object.prototype.toString.call(origin[k]) === '[object Object]' ? {} : []
          deepClone(origin[k],tag[k])
        } else {
          tag[k] =  origin[k]
        }
      }
    }
    return target
  }

第二种

  const test1 = {}
  const test2 = {}
  test2.test1 = test1
  test1.test2 = test2
  /console.log(deepClone(test2)) // 不会报错
function deepClone(origin,hashMap = new WeakMap()){
    // var a = undefined  a == null // true
    if (origin == undefined || typeof origin !== 'object'){
      return origin
    }
    if(origin instanceof Date){
      return new Date(origin)
    }
    if(origin instanceof RegExp){
      return new RegExp(origin)
    }
    const hashKey = hashMap.get(origin)
    if(hashKey) return hashKey
    const target = new origin.constructor()
    hashMap.set(origin,target)
    // 剩下的就是[] 和 {} 函数静态不拷贝
    for (const originKey in origin) {
      if(origin.hasOwnProperty(originKey)){
        target[originKey] = deepClone(origin[originKey],hashMap)
      }
    }
    return  target
  }

你可能感兴趣的:(javascript,前端,开发语言)