深拷贝详细解析

深拷贝与循环引用解决
博客探讨了JavaScript中深拷贝对象的问题,包括JSON.parse(JSON.stringify())方法的局限性,如无法处理循环引用和函数。提出了一个使用Map实现的深拷贝函数,能够处理循环引用和保留原始对象的函数。示例展示了如何处理包含循环引用和函数的对象,并进行了拷贝前后的对比。

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值