js 深度复制

typeof 方法只要是引用 除了function 会输出 Function 其他全部是object 那么复制就会有数组和{}两种方式

只需要区别object和array 分别递归复制就看要解决问题了

下面是源代码:

var copy=function(obj){
var result;
if(typeof obj!=='object'){
return;
}
if({}.toString.call(obj)==='[object Object]'){
result={};
Object.keys(obj).forEach(i=>{
if(typeof obj[i]==='object'){
result[i]=copy(obj[i]);
}else{
result[i]=obj[i];
}
});
return result;
}
if({}.toString.call(obj)==='[object Array]'){
result=[];
obj.forEach((item,index)=>{
if(typeof obj[index]==='object'){
result[index]=copy(obj[index]);
}else{
result[index]=obj[index];
}
});
return result;
}
};

原文地址:https://www.cnblogs.com/me-data/p/9533782.html