深拷貝
利用JSON.stringify和JSON.parse實現(xiàn)深度拷貝
function copy(obj) {
? let temp=JSON.parse(JSON.stringify(obj));
? return temp;
}
自寫函數(shù)實現(xiàn)深拷貝
let same=[];
function clone(obj) {
if(typeof(obj) !=="object"||!obj){
//基本類型的數(shù)據(jù):null,number,string,boolean,undefined
// function
? ? ? ? return obj;
? ? }
if(same.indexOf(obj)>-1){
//防止形成circle,比如obj={a:obj}
? ? ? ? return null;
? ? }
same.push(obj);
? ? let temp={}.toString.call(obj);
? ? let result;
? ? if(temp==='[object Array]'){
//數(shù)組
? ? ? ? result=[];
? ? ? ? obj.forEach((item,index)=>{
? ? ? ? result[index]=clone(item);
? ? ? ? });
? ? }
if(temp==='[object Object]'){
//對象
? ? ? ? result={};
? ? ? ? Object.keys(obj).forEach((key)=>{
? ? ? ? result[key]=clone(obj[key]);
? ? ? ? })
}
return result;
}