[Medium] Deep Clone
1. What is Deep Clone?
什麼是 Deep Clone?
**深拷貝(Deep Clone)**是指創建一個新物件,並且遞迴地複製原始物件及其所有巢狀物件和陣列的所有屬性。深拷貝後的物件與原始物件完全獨立,修改其中一個不會影響另一個。
淺拷貝 vs 深拷貝
淺拷貝(Shallow Clone):只複製物件的第一層屬性,巢狀物件仍然共享引用。
// 淺拷貝範例
const original = {
name: 'John',
address: {
city: 'Taipei',
country: 'Taiwan',
},
};
const shallowCopy = { ...original };
shallowCopy.address.city = 'Kaohsiung';
console.log(original.address.city); // 'Kaohsiung' ❌ 原始物件也被修改了
深拷貝(Deep Clone):遞迴複製所有層級的屬性,完全獨立。
// 深拷貝範例
const original = {
name: 'John',
address: {
city: 'Taipei',
country: 'Taiwan',
},
};
const deepCopy = deepClone(original);
deepCopy.address.city = 'Kaohsiung';
console.log(original.address.city); // 'Taipei' ✅ 原始物件不受影響
2. Implementation Methods
實作方法
方法 1:使用 JSON.parse 和 JSON.stringify
優點:簡單快速
缺點:無法處理函式、undefined、Symbol、Date、RegExp、Map、Set 等特殊型別
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// 測試
const original = {
name: 'John',
age: 30,
address: {
city: 'Taipei',
country: 'Taiwan',
},
hobbies: ['reading', 'coding'],
};
const cloned = deepClone(original);
cloned.address.city = 'Kaohsiung';
cloned.hobbies.push('swimming');
console.log(original.address.city); // 'Taipei' ✅
console.log(original.hobbies); // ['reading', 'coding'] ✅
限制:
const obj = {
date: new Date(),
func: function () {},
undefined: undefined,
symbol: Symbol('test'),
regex: /test/g,
};
const cloned = deepClone(obj);
console.log(cloned.date); // {} ❌ Date 變成空物件
console.log(cloned.func); // undefined ❌ 函式遺失
console.log(cloned.undefined); // undefined ✅ 但 JSON.stringify 會移除
console.log(cloned.symbol); // undefined ❌ Symbol 遺失
console.log(cloned.regex); // {} ❌ RegExp 變成空物件