DIV CSS 佈局教程網

JavaScript sort() 排序詳解:字典序陷阱與自訂比較函式
編輯:關於JavaScript     

只要寫過一段時間的 JavaScript,大概都用過陣列的 sort()。但許多人對它的預設行為其實誤解得頗深——尤其那個「數字排序結果怪怪的」問題,幾乎每個人都遇到過。

預設行為:字典序,不是數值序

MDN 對此有段精準描述:

若未提供 compareFunction,元素會被轉換為字串,再以字典順序(lexicographic,也就是「查字典」或「電話簿」的順序,而非數值順序)進行比較。例如字典序中 "80" 會排在 "9" 前面,但數值排序時 9 在 80 前面。

看幾個例子:

// 輸出 [1, 2, 3]
console.log([3, 2, 1].sort());

// 輸出 ["a", "b", "c"]
console.log(["c", "b", "a"].sort());

// 輸出 [1, 2, "a", "b"]
console.log(["b", 2, "a", 1].sort());

但換成多位數就露餡了:

// 輸出 [1, 10, 2, 20, 3]
console.log([3, 20, 10, 2, 1].sort());

原因就在於比較的是字串 "1"、"10"、"2"、"20"、"3",逐字元比對之下 "10" 自然小於 "2"。

自訂比較函式

function compareFunction(a, b) {
  if (a > b) {
    return -1;
  } else if (a < b) {
    return 1;
  } else {
    return 0;
  }
}

// 輸出 ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction));

比較函式的規則是:

  1. 回傳負數,a 排在較前面的索引。
  2. 回傳正數,a 排在較後面的索引。
  3. 回傳 0,順序不變。

數值排序的標準寫法是回傳差值:

[3, 20, 10, 2, 1].sort(function(a, b){ return a - b; });   // 升冪
[3, 20, 10, 2, 1].sort(function(a, b){ return b - a; });   // 降冪

用閉包控制升降冪

function compareFunction(flag) {
  flag = flag ? flag : "asc";
  return function(a, b) {
    if (a > b) {
      return flag === "desc" ? -1 : 1;
    } else if (a < b) {
      return flag === "desc" ? 1 : -1;
    } else {
      return 0;
    }
  };
}

// 輸出 ["1", "Benjamin", "zuojj"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction()));

// 輸出 ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction("desc")));

把 flag 關在閉包裡,回傳一個比較函式。這種「函式產生器」模式在需要動態調整排序方向時很好用。

undefined 與稀疏陣列

MDN 提到 sort 的行為在 JavaScript 1.1 與 1.2 之間改變過。1.1 時期在某些平台上 sort 甚至無法運作;1.2 之後則不再把 undefined 元素轉為 null,而是把它們排到陣列尾端。

var arr = [];
arr[0] = "Ant";
arr[5] = "Zebra";

// 輸出 ["Ant", 5: "Zebra"]
console.log(arr);

// 輸出 6
console.log(arr.length);

// 輸出 "Ant*****Zebra"
console.log(arr.join("*"));

// 排序
var sortArr = arr.sort();

// 輸出 ["Ant", "Zebra"]
console.log(sortArr);

// 輸出 6
console.log(sortArr.length);

// 輸出 "Ant*Zebra****"
console.log(sortArr.join("*"));

這段範例很值得細看。原本 arr 是一個稀疏陣列,索引 1 到 4 是空洞。join 時空洞被視為空字串,所以輸出 "Ant*****Zebra"(Ant 加五個星號再加 Zebra)。排序之後,undefined 被移到尾端,於是變成 "Ant*Zebra****"。長度仍然是 6,因為排序不會移除空位。

幾個實務提醒

  • sort 會改動原陣列。若需要保留原資料,先複製:[...arr].sort() 或 arr.slice().sort()。
  • 比較函式必須一致。若比較結果會隨呼叫次數改變,排序結果將不可預期。
  • 物件陣列要指定欄位:users.sort((a, b) => a.name.localeCompare(b.name))。
  • 字串排序可用 localeCompare,它會依地區語言規則處理,比直接相減或大小於更適合多語言內容。

參考資料:MDN - Array.prototype.sort

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved