//淺拷貝 function shallowCopy(src){ if(typeof src != 'object'){ return src; } var dest = Array.isArray(src) ? [] : {}; for(var p in src){ if(src.hasOwnProperty(p)){ dest[p] = src[p]; } } return dest; } //深拷貝 function deepCopy(src){ if(typeof src != 'object'){ return src; } var dest = Array.isArray(src) ? [] : {}; for(var p in src){ if(src.hasOwnProperty(p)){ dest[p] = typeof(src[p]) == 'object' ? deepCopy(src[p]) : src[p]; } } return dest; } //JSON.parse深拷貝,在基本型別的拷貝上夠用了 //缺點:不支援NaN,Infinity,精確的浮點數,function和迴圈引用, 屬性是undefined或null的時候會被移除掉 var obj2 = JSON.parse(JSON.stringify(obj)); //陣列淺拷貝 arr.slice(0) arr.concat() var [...arr2] = arr; //物件淺拷貝 var {...obj2} = obj; //Object.assign只對頂層屬性進行復制,並且是淺拷貝 var obj2 = Object.assign({},obj);