深拷贝

<script>
let obj = {

            name:"张三",
            children:{
                boy:['liming','lis',undefined,function(){}],
                girl:['ss']
            },
            wife:{
                name:'xixi'
            }
        }

        //deep copy
        function deepCopy(object){
            let obj = object instanceof Array ? [] : {};
            for (const [k,v] of Object.entires(object)) {
                obj[k] = typeof v == "object" ? deepCopy(v) : v;
            }
            return obj;
        }

        let obj2 = JSON.stringify(obj);
        let obj3 = JSON.parse(obj2);
        console.log(obj3);


        //代码繁杂版本
        function copy(target){
            let result;
            if(typeof target === "object"){
                if(Array.isArray(target)){
                    result = [];
                    for (const i in target) {
                        result.push(target[i])
                    }
                }else if(target === null){
                    result = null;
                }else if(target.constructor === RegExp){
                    result = target;
                }else{
                    result = {};
                    for (const i in target) {
                        result[i] = copy(target[i]);
                    }
                }
            }else{
                result = target;
            }
            return result;
        }

        let a = copy(obj);
        console.log(a);


    </script>
posted @ 2021-02-09 11:48  HF10  阅读(48)  评论(0)    收藏  举报