Skip to main content

深拷贝

// 不考虑拷贝普通类型
function deepCopy(obj,copy){

var copy = copy || {};
for(var i in obj){
if(typeof obj[i] === 'object'){
copy = obj[i].constructor == Array?[]:{};
deepCopy(obj[i],copy);
}else{
copy[i] = obj[i];
}
}

return copy;
};
// 考虑普通类型
function deepCopy(obj){
let newObj = null;
// 普通类型直接返回
if(!isNormalType(obj)){
return obj;
}

newObj = isNormalType(obj)==='object'?{}:[];

for (var i in obj) {
if (!isNormalType(obj[i])) {
newObj[i] = obj[i];
} else {
newObj[i] = deepCopy(obj[i]);
}
}
return newObj;

function isNormalType(item){
var type = Object.prototype.toString.call(item);
if(type=='[object Array]'){
return 'array';
}else if(type=='[object Object]'){
return 'object';
}else{
return false;
}
}
}


var obj = [];
var newObj = deepCopy(obj);
console.log(Object.prototype.toString.call(obj));