Array.prototype.sort() 方法的運作原理
sort() 方法用於對 JavaScript 陣列就地排序,即直接修改原陣列,並回傳排序後的陣列。它的行為取決於是否提供比較函式 (compare function)。
1.沒有比較函式時 (sort())
如果沒有提供比較函式,sort() 預設會將陣列元素轉換為字串,並依照 Unicode 字典順序 (lexicographic order) 進行排序。
範例
const arr = [100, 2, 50, 20, 5];
arr.sort();
console.log(arr);
// ➝ [100, 2, 20, 5, 50] // 按字串排序,"100" < "2" < "20" < "5" < "50"為什麼結果不如預期?
因為 sort() 預設是按照字串的 Unicode 值來排序,而不是數字大小!
2.提供比較函式 (sort(compareFn))
為了正確排序數值,必須提供比較函式 (compare function),它應該回傳:
- 負數 (
< 0):a排在b之前 - 零 (
0):保持原順序 - 正數 (
> 0):a排在b之後
數字排序
const arr = [100, 2, 50, 20, 5];
arr.sort((a, b) => a - b);
console.log(arr);
// ➝ [2, 5, 20, 50, 100] // 依數值大小排序如何運作?
100 - 2 > 0→2排在100前面2 - 50 < 0→2保持原位50 - 20 > 0→20排在50前面- 依此類推,直到排序完成。
當 sort((a, b) => a - b) 遇到字串時:
- 數字型字串 (
"10","5") 會轉換成數字 - 非數字字串 (
"apple","banana") 轉換失敗,結果變成NaN NaN參與比較時,無法確保正確排序,結果可能是未定行為(不同的 JavaScript 引擎可能有不同表現)
字串排序
對於字串,應該使用 localeCompare():
const names = ["Banana", "apple", "Cherry"];
names.sort((a, b) => a.localeCompare(b));
console.log(names);
// ➝ ["apple", "Banana", "Cherry"]這確保了符合語言的字母順序,例如 a 排在 B 之前。
