手写深拷贝

代码

<script>
    let obj1 = {
        age: 20,
        name: 'xxx',
        address: {
            city: 'beijing'
        },
        arr: ['a', 'b', 'c']
    }
    let obj2 = deepClone(obj1);

    function deepClone(obj = {}){
        let result;
        if(typeof obj != 'object' || obj == null){
            return obj;
        }

        if(obj instanceof Array){
            result = []
        } else {
            result = {}
        }

        for(let key in obj){
            if(obj.hasOwnProperty(key)){
            	// 递归调用
                result[key] = deepClone(obj[key])
            }
        }

        return result;
    }
	obj2.age = 30
    console.log(obj1.age);

</script>

输出

20

发布了23 篇原创文章 · 获赞 0 · 访问量 522

猜你喜欢

转载自blog.csdn.net/qq_33084055/article/details/103824436