JS对象深拷贝

方法一:

JSON.parse(JSON.stringify(obj))
缺点:不能复制对象里的function,symbol,undefined

            var obj = {
                _name: "小明",
                _age:18,
                skill: function() {
                    console.log('1');
                },
                play: function() {
                    console.log('2')
                },
                a: undefined
            }

var copyObj = JSON.parse(JSON.stringify(obj));
console.log(copyObj);//{_name: "小明", _age: 18}
copyObj.skill();//copyObj.skill is not a function
                        

方法二:递归

            var obj = {
                _name: "小明",
                _age:18,
                skill: function() {
                    console.log('1');
                },
                play: function() {
                    console.log('2')
                },
                a: undefined
            }

            function deepCopy(obj){
                let copyObj = Array.isArray(obj)?[]:{};
                for(var key in obj){
                    copyObj[key] = typeof(obj[key])==="object"?deepCopy(obj[key]):obj[key];
                }
                console.log(copyObj==obj);//false
                return copyObj;
            }
            
            console.log(deepCopy(obj));//{_name: "小明", skill: ƒ, play: ƒ, a: undefined}

你可能感兴趣的:(JS对象深拷贝)