手写深拷贝函数

const a = {
    a:1,
    b:{b:1},
    c:[1,2,3],
    d(){
        console.log('d');   
    },
    e:{
        a:[1,2],
        b:{bb:12},
        c(){console.log('cc');
        }
    }
}
const deepClone = (value) => {
    if(value instanceof Array){
        const res = []
        for (const item of value) {
            res.push(deepClone(item))
        }
        return res
    }else if(typeof value === 'function'){
       return value
    }
    else if(value instanceof Object){
        const res = {}
        for (const key in value) {
            res[key] =deepClone(value[key]) 
        }
        return res
    }else{
        return value
    }
}


const b = deepClone(a)
console.log('res',b);
a.b.b = 2
console.log(b.b.b,a.b.b);
a.c.push('4')
console.log(b.c,a.c);
console.log(a.d);
a.e.a.push('3')
console.log(a.e.a,b.e.a);
a.e.b.c = 1
console.log(a.e.b,b.e.b);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容