let obj={name:'jack',address:'shanghai'}
let o = {...obj};
obj.name = 'hello';
console.log(o); //=>{name: "jack", address: "shanghai"}
複製代碼
這個看起來有點像深拷貝是否是? 別急再來一點變化。json
let obj={name:'jack',address:{city:'shanghai',num:1}}
let o = {...obj};
obj.name = 'hello';obj.address.city='beijing'
console.log(o);
//{name: "jack", address:{city: "beijing",num: 1}}
複製代碼
因此咱們知道深拷貝不單單是一維不影響而且朵惟也不影響。因此...運算符是淺拷貝;
數組
2.slice/concat 這兩個方法和1是同樣的 一維的時候是深拷貝 可是多維是淺拷貝bash
function deepClone(obj){
if(obj == null) return obj;
if(obj instanceof Date) return new Date(obj);
if(obj instanceof RegExp) return new RegExp(obj);
if(typeof obj !=='object') rerurn obj;
let cloneObj = new obj.constructor;
//找到數組或者對象的原型;
for(let key in obj){
if(obj.hasOwnPrototype(key){
//實現遞歸拷貝
cloneObj[key] = deepClone(obj[key]);
}
}
return cloneObj;
}
let obj = {name:1,address:{name:'shanghai',num:1}};
複製代碼