js數組和對象的深淺拷貝
數組和對象屬于引用型數據類型。直接賦值實際上就是給了訪問地址
let a = [1,2,3]; let b = a; b[0] = 0; console.log(a); //[0,2,3] console.log(b); //[0,2,3]
//對象同理
以上直接賦值方式為淺拷貝,在實際應用中,需要清楚需要哪種拷貝(多為深拷貝)。
數組和對象的深拷貝都可以用循環做到,但是不推薦。以下是比較好的方法:
//數組 let a = [1,2,3]; let b = [...a]; b[0] = 0; console.log(a) //[1,2,3] console.log(b) //[0,2,3] //對象 //方法一,json字符串,缺點,不好處理函數 let obj = {name:"張三"}; let obj1=JSON.parse(JSON.stringify(obj)); obj1.name = "李四"; console.log(obj);//{name:"張三"}; console.log(obj1);//{name:"李四"}; //方案二:遞歸解析法 function copyObject(obj){ let newObj = obj.constructor === Array?[]:{}; for(var i in obj){ if(typeof obj[i] === 'object'){ newObj[i] = arguments.callee(obj[i]); } else{ newObj[i]=obj[i]; } } return newObj; } function copyAll(type){ let obj2; if(typeof type === 'object'){ obj2 = copyObject(type); }else{ obj2 = type; } return obj2; }
浙公網安備 33010602011771號