js淺拷貝和深拷貝
阿新 • • 發佈:2018-11-04
資料準備:
var o = { //基本資料型別 name:'hxj', //引用資料型別中的Object user:{ age:23, id:201 }, //引用資料型別中的Array friend:['zs','yy','f'], }
淺拷貝
function Copy(o,copyO) { var copyO = copyO || {}; for(var i in o){ copyO[i] = o[i]; } return copyO; }
測試:
var copy1 = Copy(o); copy1.name = 'zs'; copy1.friend.push('pp'); copy1.user[name] = 'user1'; console.log('o:',o); console.log('copyO:',copy1);
深拷貝
function deepCopy(o,copyO){ var copyO = copyO || {}; for(var i in o){ if(o[i] instanceof Array){ copyO[i] = []; //如果屬性是陣列或物件,則遞迴他的屬性,直到屬性為基本型別deepCopy(o[i],copyO[i]); }else if(o[i] instanceof Object){ copyO[i] = {}; deepCopy(o[i],copyO[i]); }else{ copyO[i] = o[i]; } } return copyO; }
測試:
var copyO2 = deepCopy(o); copyO2.name = 'hh'; copyO2.friend.push('pp'); console.log('o:',o); console.log('copyO:',copyO2);