const arr = [10, 50, 51, 100];
arr.sort();
console.log(arr); // [10, 100, 50, 51] ❌ 非數值序
原因:`sort()` 預設將元素轉字串比較,`"100" < "50"`(字典序)。
// 數值升序
arr.sort((a, b) => a - b); // [10, 50, 51, 100]
// 數值降序
arr.sort((a, b) => b - a); // [100, 51, 50, 10]
// 物件陣列按屬性排序
const users = [{age:25},{age:18},{age:30}];
users.sort((a, b) => a.age - b.age);
| 特性 | 說明 | 範例 |
|---|---|---|
| 原地修改 | sort() 直接改變原陣列,回傳同一參考 | const b = arr.sort(); b === arr // true |
| 預設字串序 | 無比較函式時,元素轉字串按 Unicode 排序 | [10,2,30].sort() → [10,2,30] |
| 穩定排序 | ES2019+ 保證相等元素相對順序不變 | 相同 age 的用戶保持原順序 |
// 1. 數值升/降序
(a, b) => a - b // 升序
(a, b) => b - a // 降序
// 2. 字串區域敏感排序
(a, b) => a.localeCompare(b, "zh-Hant") // 繁體中文筆畫/拼音序
// 3. 多鍵值排序(先按 age 升序,再按 name 降序)
(a, b) => a.age - b.age || b.name.localeCompare(a.name)
// 4. null/undefined 置後
(a, b) => (a == null) - (b == null) || a - b
// 淺拷貝後排序
const sorted = [...arr].sort((a, b) => a - b);
// 或用 toSorted()(ES2023+,Stage 3 提案,部分環境已支援)
const sorted = arr.toSorted((a, b) => a - b);
// 裝飾-排序-去裝飾
const decorated = arr.map((v, i) => ({ v, i, key: computeKey(v) }));
decorated.sort((a, b) => a.key - b.key || a.i - b.i);
const result = decorated.map(d => d.v);
localeCompare 處理多語言字串排序。