js高级进阶——手动实现深拷贝函数

主要考察目标:

  1. 数据类型校验
  2. 循环引用
    function deepClone(data, hash = new WeakMap) {
      if (data == undefined) return data;
      if (typeof data !== 'object') return data;
      if (data instanceof RegExp) return new RegExp(data)
      if (data instanceof Date) return new Date(data)

      var v = hash.get(data)
      if (v) return v

      var instance = new data.constructor
      hash.set(data, instance)
      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          instance[key] = deepClone(data[key], hash)
        }
      }
      return instance
    }

    var a = {
      name: 'bob',
      desc: {
        age: 12
      }
    }

    var b = deepClone(a)
    b.desc.age = 100
    console.log(b)
    console.log(a)

    // js循环引用
    var t = {}
    t.t = t
    console.log(deepClone(t))

今日查看Vuex源码,工具函数中定义了一个deepCopy函数,也可以达到深克隆效果,只考虑了对数组和对象类型进行深拷贝,不过用于日常的业务功能开发,肯定足够了。

function find(list, fn) {
  return list.filter(fn)[0]
}

function deepCopy(obj, cache = []){
  if(obj === null || typeof obj !== 'object'){
    return obj
  }

  const hit = find(cache, v => v.original === obj)
  if(hit){
    return hit.copy
  }

  const copy = Array.isArray(obj) ? [] : {}

  cache.push({
    original: obj,
    copy
  })

  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache)
  })
  return copy
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值