[5, 10, 1].sort();
// 結果:[1, 10, 5] ❌
// 預期:[1, 5, 10]
`Array.prototype.sort()` **不傳比較函數時**,會將所有元素轉為字串,按 UTF-16 碼位逐字符比較:
'10' vs '5' → '1' (49) < '5' (53) → '10' 排在 '5' 前面
'2' vs '10' → '2' (50) > '1' (49) → '2' 排在 '10' 後面
// 升序
arr.sort((a, b) => a - b);
// 降序
arr.sort((a, b) => b - a);
const users = [{age:20, name:'A'}, {age:18, name:'B'}, {age:20, name:'C'}];
// 單鍵:age 升序
users.sort((a, b) => a.age - b.age);
// 多鍵:age 升序,同 age 時 name 降序
users.sort((a, b) => a.age - b.age || b.name.localeCompare(a.name));
const cities = ['北京', '上海', '廣州', '深圳'];
// 使用 Intl.Collator(現代、高效能、支援選項)
const collator = new Intl.Collator('zh-CN', { sensitivity: 'base' });
cities.sort(collator.compare); // 按拼音排序
// 或 localeCompare
cities.sort((a, b) => a.localeCompare(b, 'zh-CN', { sensitivity: 'base' }));
const dates = ['2024-01-15', '2023-12-01', '2024-03-20'];
// ISO 字串可直接字典序排序
dates.sort(); // 正確
// Date 對象
const dateObjs = [new Date('2024-01-15'), new Date('2023-12-01')];
dateObjs.sort((a, b) => a - b); // Date 隱式轉時間戳比較
const mixed = [3, null, 1, undefined, 2];
mixed.sort((a, b) => {
if (a == null && b == null) return 0;
if (a == null) return 1; // null/undefined 排後
if (b == null) return -1;
return a - b;
}); // [1, 2, 3, null, undefined]
// ❌ 返回布爾值(舊版瀏覽器可能工作,但不符合規範)
arr.sort((a, b) => a > b);
// ❌ 字串數值混排
['10', 5, '2'].sort((a, b) => a - b); // 隱式轉型,結果不可預期
// ✅ 統一類型後再排
const nums = ['10', 5, '2'].map(Number);
nums.sort((a, b) => a - b);
interface User { age: number; name: string; }
const users: User[] = [...];
// 類型守衛確保比較函數參數正確
users.sort((a: User, b: User): number => a.age - b.age);
// 通用排序工具
function sortBy(arr: T[], key: keyof T | ((item: T) => number), dir: 'asc'|'desc' = 'asc') {
const getter = typeof key === 'function' ? key : (o: T) => o[key];
const mul = dir === 'asc' ? 1 : -1;
return arr.slice().sort((a, b) => (getter(a) - getter(b)) * mul);
}
`[5,10,1].sort()` 返回 `[1,10,5]` 是 **JavaScript 歷史遺留設計**(ECMA-262 1st edition 定義)。**永遠為數值/物件排序提供比較函數**,養成 `sort((a,b)=>a-b)` 肌肉記憶。現代項目推薦使用 `Intl.Collator` 處理多語言字串排序,封裝通用 `sortBy` 工具函數提升開發效率。