淺層複製 ( shallow copy )
for in 寫法
// 淺層複製
var family = {
home: '小黑家',
members:{
mom: '老媽',
father: '老爸',
black: '小黑',
}
}
var newFamily = {};
for(var key in family){
console.log(key); // home members (family第一層屬性)
newFamily[key] = family[key];
}
console.log(newFamily,family);
// 修改第一層屬性
newFamily.home = '大雄家';
console.log(newFamily,family); // 大雄家 小黑家
console.log(newFamily === family); // false
// 修改第二層屬性
newFamily.members.black = '大黑';
console.log(newFamily,family); // 大黑 大黑
console.log(newFamily === family); // false
// 且會發現 兩個同時都會改 所以只能做到第一層的複製
jQuery 寫法
var newFamily2 = jQuery.extend({},family);
ES6 寫法
var newFamily3 = Object.assign({},family);
深層複製(deep copy)
透過 JSON.stringify 先轉字串 再透過 JSON.parse 轉成物件
var family = {
home: '小黑家',
members:{
mom: '老媽',
father: '老爸',
black: '小黑',
}
}
var newFamily4 = JSON.parse(JSON.stringify(family));
newFamily4.home = '小白家';
newFamily4.members.black = '大黑';
console.log(family,newFamily4); // 小黑家 小黑 , 小白家 大黑
console.log(family === newFamily4); // false
那今天的介紹就到這裡
若有任何問題 或 內容有誤
都可以跟我說唷