淺拷貝 vs 深拷貝
| 特性 | 淺拷貝 | 深拷貝 |
| 定義 | 複製第一層引用 | 遞迴複製所有層級 |
| 巢狀物件影響 | 修改巢狀物件會影響原陣列 | 完全獨立,互不影響 |
| 效能 | 極快 | 較慢 (視深度/大小) |
| 適用場景 | 扁平陣列、基本型別陣列 | 巢狀物件/陣列、需完全隔離 |
淺拷貝方法 (扁平陣列適用)
1. Array.prototype.slice() - 經典做法
const arr = [1, 2, 3];
const arr2 = arr.slice(0); // 或 arr.slice()
arr2[0] = 100;
console.log(arr); // [1, 2, 3] ✅ 未受影響
console.log(arr2); // [100, 2, 3]
2. 展開運算子 [...arr] - ES6 推薦
const arr = [1, 2, 3];
const arr2 = [...arr];
arr2.push(4);
console.log(arr); // [1, 2, 3]
console.log(arr2); // [1, 2, 3, 4]
3. Array.from()
const arr2 = Array.from(arr);
4. Array.concat()
const arr2 = [].concat(arr);
5. Object.assign() (較少用於陣列)
const arr2 = Object.assign([], arr);
深拷貝方法 (巢狀結構必須)
1. JSON 序列化/反序列化 (簡單但有限制)
const arr = [{a: 1}, [2, 3], new Date()];
const arr2 = JSON.parse(JSON.stringify(arr));
// ⚠️ 限制:
// - 無法處理 Function、RegExp、Date (變字串)、undefined、Symbol
// - 循環引用會拋錯
// - 原型鏈丟失 (實例變成純物件)
2. 結構化複製演算法 structuredClone() - 現代標準 (推薦)
// 支援:Date, RegExp, Map, Set, ArrayBuffer, Blob, File, ImageData 等
// 支援循環引用
// 不支援:Function, DOM 節點, Error, 弱引用
const arr = [{a: 1, date: new Date()}, [2, 3]];
const arr2 = structuredClone(arr);
arr2[0].a = 999;
arr2[1].push(4);
console.log(arr[0].a); // 1 ✅
console.log(arr[1]); // [2, 3] ✅
3. Lodash cloneDeep (生產級、功能最完整)
import { cloneDeep } from 'lodash';
const arr = [{a: 1, fn: () => {}}, new Map([[1,2]])];
const arr2 = cloneDeep(arr);
// 函式會被複製 (但無法真正深拷貝閉包),Map/Set 正確複製
4. 手寫遞迴深拷貝 (面試常考)
function deepClone(obj, hash = new WeakMap()) {
// 基本型別直接返回
if (obj === null || typeof obj !== 'object') return obj;
// 日期、正則特殊處理
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
// 循環引用檢測
if (hash.has(obj)) return hash.get(obj);
// 建構新物件/陣列
const clone = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj));
hash.set(obj, clone);
// 遞迴複製自有屬性
for (const key of Object.keys(obj)) {
clone[key] = deepClone(obj[key], hash);
}
// Symbol 屬性
for (const sym of Object.getOwnPropertySymbols(obj)) {
clone[sym] = deepClone(obj[sym], hash);
}
return clone;
}
效能基準測試 (參考)
// 測試資料:10000 筆扁平陣列 vs 1000 筆深度 3 巢狀物件
const flat = Array.from({length: 10000}, (_, i) => i);
const deep = Array.from({length: 1000}, (_, i) => ({id: i, data: {vals: [i, i+1]}}));
console.time('slice'); for(let i=0;i<100;i++) flat.slice(); console.timeEnd('slice'); // ~2ms
console.time('spread'); for(let i=0;i<100;i++) [...flat]; console.timeEnd('spread'); // ~3ms
console.time('JSON'); for(let i=0;i<100;i++) JSON.parse(JSON.stringify(deep)); console.timeEnd('JSON'); // ~120ms
console.time('structuredClone'); for(let i=0;i<100;i++) structuredClone(deep); console.timeEnd('structuredClone'); // ~40ms
console.time('lodash'); for(let i=0;i<100;i++) cloneDeep(deep); console.timeEnd('lodash'); // ~80ms
選擇指南
| 場景 | 推薦方法 | 備註 |
| 基本型別扁平陣列 | [...arr] 或 arr.slice() | 語法簡潔、效能最佳 |
| 含 Date/RegExp/Map/Set 且無循環引用 | structuredClone() | 原生、快速、標準 |
| 含循環引用 | structuredClone() 或 Lodash | JSON 會報錯 |
| 含 Function/DOM/Error | Lodash cloneDeep | 最完整但較慢 |
| 不支援 structuredClone 環境 (舊瀏覽器) | Lodash 或手寫遞迴 | Polyfill 可用 core-js |
面試必考點總結
slice()、[...arr]、concat() 皆為淺拷貝
- 淺拷貝只複製第一層,巢狀物件共享引用
JSON.parse(JSON.stringify()) 是偽深拷貝,有諸多限制
- 現代瀏覽器首選
structuredClone() (支援循環引用、內建型別豐富)
- 手寫深拷貝需處理:型別判斷、循環引用、原型鏈、Symbol、特殊物件