深拷贝详细解析

JSON.parse(JSON.stringify())

循环引用会报错, 不能拷贝函数

 function deepClone1(target) {
    const result = JSON.parse(JSON.stringify(target))
    return result
}

 const obj = {
     a: 1,
     b: ['e', 'f', 'g'],
     c: {h: 20},
     d: function() {}
 }
 // 循环引用
 obj.b.push(obj.c)
 obj.c.j = obj.b
 // 不能拷贝函数
 const result = deepClone1(obj)
 console.log(obj)
 console.log(result)

究极解决方案:


function deepClone2(target, map = new Map()) {
    if(typeof target === 'object' && target !== null) {
        // 克隆数据之前,进行判断,数据之前是否客隆过
        let cache = map.get(target)
        if(cache) {
            return cache
        }
        // 判断目标数据的类型
        let isArray = Array.isArray(target)
        // 创建一个容器
        const result = Array.isArray(target) ? [] : {}
        map.set(target, result)
        // 如果目标为数组
        if(isArray) {
            target.forEach((item, index) => {
                result[index] = deepClone2(item, map)
            })
        } else {
            Object.keys(target).forEach(key => {
                result[key] = deepClone2(target[key], map)
            })
        }
        return result
    } else {
        return target
    }
}

 const obj = {
     a: 1,
     b: ['e', 'f', 'g'],
     c: {h: 20},
     d: function() {}
 }
 // 循环引用
 obj.b.push(obj.c)
 obj.c.j = obj.b
 const result = deepClone2(obj)
 console.log(obj)
 console.log(result)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值