js 简单的深拷贝

本题是通过@郝晨光 的文章受到的启发,学习来的,大家有兴趣可以看一下,而且我觉得这种写法非常通俗易懂,工作中也足够去使用了。

复制代码
function DeepClone(target){
    let result
    //1、先判断当前是否为对象 
    if(typeof target === 'object'){
        //2、判断当前是否为数组,如果是,设置result为数组,并且循环递归 push赋值
        if(Array.isArray(target)){
            result = []
            for (const key in target) {
                result = DeepClone(target[key])
            }
        //3、判断当前是否为null,如果是直接赋值
        }else if(target === null){
            result = null
        //4、判断当前是否为RegExp,如果是直接赋值
        }else if(target.constructor === RegExp){
            result = target
        }else{
            // 5、普通对象直接循环,递归
            result = {}
            for (const i in target) {
                result[i] = DeepClone(target[i])
            }
        }
    }else{
        //如果不是对象类型直接赋值
        result = target
    }

    return result
}

let obj1 = {
    a: {
        c: /a/,
        d: undefined,
        b: null
    },
    b: function () {
        console.log(this.a)
    },
    c: [
        {
            a: 'c',
            b: /b/,
            c: undefined
        },
        'a',
        3
    ]
}
let obj2 = DeepClone(obj1);
obj1.a.c = /b/
console.log(obj1)
console.log(obj2)
复制代码

 

posted @   First·林肯  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示