关于深拷贝(含数组对象)

时间:2023-01-23 19:51:44

 

1、普通的深拷贝(对象中不含数组的话,可以使用该方法)

var complex = {persons:['one','two'],age:'20,20,20',arr:[1,4,2]};
console.log(deepCopyObj(complex));

如果含有数组的话,会将数组转为下面这种形式,{0:‘one’,1:'two'}

 关于深拷贝(含数组对象)

function deepCopyObj(obj){ 
    var newcopy = {};
    if(typeof obj =='object') {
        for(var key in obj){ console.log(key,obj[key]);
            newcopy[key] = typeof obj[key] =='object' ? deepCopyObj(obj[key]) : obj[key];
        }
    }
    return newcopy;
}

 

针对json形式的对象那个,满足两个条件:1、键名是数值 2、添加一个length属性,可以转换成数组

//json对象转为数组 满足两个条件:1、键名是数值 2、添加一个length属性
var arr = [10,20,30];
var copyobj = deepCopyObj(arr);
console.log('copyobj',copyobj);  //{0:10,1:20,2:30}
copyobj.length = 3;        //添加length属性
var copeArr = [].slice.call(copyobj,0); //转数组
console.log('copeArr',copeArr); // [10,20,30]

 

 

2、改进的方法

function deepCopyAdvanced(obj){
    if(obj instanceof Array){
        var copy = [];
        for(var i=0,len=obj.length;i<len;i++){
            copy[i] = typeof obj[i] =='object' ? deepCopyAdvanced(obj[i]) : obj[i];
        }
        return copy;
    }else if(obj instanceof Object){
        var copy = {};
        for(var key in obj){ 
            copy[key] = typeof obj[key] =='object' ? deepCopyAdvanced(obj[key]) : obj[key];
        }
        return copy;
    }

    return obj;
}