//浅拷贝 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);