深拷贝纯代码

一、JS深拷贝JSON.parse(JSON.string())的缺点不能拷贝函数,Date、正则表达式等,为解决这个问题,纯代码实现深拷贝功能,记录一下。

调用代码:

	let  time = new Date()
    const sym = Symbol("symbol")
    let obj = {
        a:1,
        b:2,
        c:{a:1, b:2},
        d: time,
        e: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/,
        [sym]:"22222",
        way:function(){
            return a+b
        }
    }
 
    let obj2 = deepCopy(obj)

结果展示

在这里插入图片描述

深拷贝实现代码如下:

   function deepCopy(source , keepMap = new Map){
        //判断是否为对象,不是直接返回数据
        if( typeof source !== "object"  || source == null){
            return source
        }
        //  避免循环引用
        if(keepMap.has(source)){
            return keepMap.get(source);
        }
        let type;
        if(Array.isArray(source)){
            type = []
        }else if(source instanceof Date){
            type = new Date(source)
        }else if(source instanceof RegExp){ //
            type = new RegExp(source.source, source.flags)
        }else{
            type = {}
        }
     
        keepMap.set(source, type)
        
        for (const key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {

                if(typeof source[key] === "object" && source[key] !== null){ 
                    type[key] = deepCopy(source[key], keepMap)
                }else{
                    type[key] = source[key]
                }   
            }
        }
        //获取所有的Symbol属性
        const symbols = Object.getOwnPropertySymbols(source)
        for (const symkey of symbols) {           
            const element = source[symkey];
            type[symkey] = deepCopy(element, keepMap)
        }         
        return type
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值