萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Array.sort() 陷阱:默認字串排序導致數值排序錯誤的根因與解決方案

現象重現

[5, 10, 1].sort(); 
// 結果:[1, 10, 5] ❌
// 預期:[1, 5, 10]

根因:默認按 Unicode 字串排序

`Array.prototype.sort()` **不傳比較函數時**,會將所有元素轉為字串,按 UTF-16 碼位逐字符比較:

'10' vs '5' → '1' (49) < '5' (53) → '10' 排在 '5' 前面
'2' vs '10' → '2' (50) > '1' (49) → '2' 排在 '10' 後面

正確解決方案

1. 數值升序/降序

// 升序
arr.sort((a, b) => a - b);

// 降序
arr.sort((a, b) => b - a);

2. 物件屬性排序

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));

3. 字串本地化排序(中文拼音/多語言)

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' }));

4. 日期排序

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 隱式轉時間戳比較

5. 空值/undefined 置後

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]

進階:穩定排序與效能

  • **ES2019 規範要求 sort 穩定**(相等元素保持原序),現代瀏覽器均已實現。
  • 大數據量(>10萬)排序時,比較函數開銷佔主導:
    • 預計算排序鍵:`arr.map(x => ({key: computeKey(x), value: x})).sort((a,b)=>a.key-b.key).map(x=>x.value)`
    • 或使用 TypedArray + WebAssembly 排序

常見錯誤模式

// ❌ 返回布爾值(舊版瀏覽器可能工作,但不符合規範)
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);

TypeScript 型別安全排序

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` 工具函數提升開發效率。

copyright © 萬盛學電腦網 all rights reserved