如何实现浅拷贝和深拷贝

一、浅拷贝的实现方法

1.Object.assign方法
        let obj1={
            name:"aaa",
        }
        let obj2={
            age:20
        }

        let obj3=Object.assign(obj1,obj2)
        // obj3.age=30
        console.log(obj1);
        console.log(obj3);
        console.log(obj1==obj3);
        console.log(obj1===obj3);

结果为:

如何实现浅拷贝和深拷贝_第1张图片

 2.直接赋值
            let obj1={
                name:"aaa",
                age:20,
                hobby:{
                    life:"eat"
                }
            }
            let obj2=obj1
            obj2.name="hhh"
            console.log(obj1);
            console.log(obj2);
            console.log(obj1==obj2);
            console.log(obj1===obj2);

如何实现浅拷贝和深拷贝_第2张图片

 二、深拷贝的实现方法

1.递归
let obj1={
                    name:"aaa",
                    age:20,
                    hobby:["1","2","3"]
                }
                function deepClone(obj){
                    if(obj===null ||typeof obj!=="object"){
                        return obj
                    }
                    let obj2
                    if(obj&&typeof obj==="object"){
                        obj2={}
                        for(let key in obj){
                            if(obj.hasOwnProperty(key)){
                                obj2[key]=deepClone(obj[key])
                            }
                        }
                    }
                    if(Array.isArray(obj)){
                        obj2=[]
                        for(let i in obj){
                            obj2.push(deepClone(obj[i]))
                        }
                    }
                    return obj2
                }
                let obj3=deepClone(obj1)
                // obj3.hobby[1]=5
                console.log(obj3);
                console.log(obj1);
                console.log(obj1==obj3);
                console.log(obj1===obj3);

输出结果为:

如何实现浅拷贝和深拷贝_第3张图片

 2.json
let obj1={
                    name:"aaa",
                    age:20,
                    hobby:["1","2","3"]
                }

                let obj2=JSON.parse(JSON.stringify(obj1))
                obj2.hobby[2]="45"
                console.log(obj2);
                console.log(obj1);
                console.log(obj1==obj2);
                console.log(obj1===obj2);

输出结果为:

如何实现浅拷贝和深拷贝_第4张图片

 

你可能感兴趣的:(面试题,前端,javascript)