js手写深拷贝,考虑各种数据类型

  • Post author:
  • Post category:其他


function cloneDeep(obj, map = new WeakMap()) {
      if(typeof obj !== 'object' || obj == null) return obj

      //避免循环引用
      const objFromMap = map.get(obj)
      if(objFromMap) return objFromMap

      let target = {}
      map.set(obj, target)
      if(obj instanceof Map){
        target = new Map()
        obj.forEach((v, k) => {
          const v1 = cloneDeep(v, map)
          const k1 = cloneDeep(k, map)
          target.set(k1, v1)
        })
      }

      if(obj instanceof Set) {
        target = new Set()
        obj.forEach(v => {
          const v1 = cloneDeep(v, map)
          target.add(v1)
        })
      }

      if(obj instanceof Array) {
        target = obj.map(item => cloneDeep(item, map))
      }

      for(const key in obj) {
        const val = obj[key]
        const val1 = cloneDeep(val, map)
        target[key] = val1
      }
      return target
    }



测试

 const obj = {
      x: 100,
      y: function() {
        console.log(this.x)
      },
      m: new Map([['x', 1], ['y', 2]]),
      s: new Set([10, 20, 30]),
      p: {
        info: {
          city: 'beijing'
        }
      }
    }
    const obj1 = cloneDeep(obj)
    obj1.p.info.city = 'shanghai'
    console.log(obj.p.info.city)//beijing



版权声明:本文为weixin_41637876原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。