DIV CSS 佈局教程網

JavaScript sort() 排序詳解:字典序陷阱與自訂比較函數
編輯:JavaScript基礎知識     

寫 JavaScript 一段時間後,你一定用過 sort。它是 Array.prototype 上的方法,簽名為 array.sort(compareFunction)。MDN 對它的描述是:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic (“dictionary” or “telephone book,” not numerical) order. For example, “80” comes before “9” in lexicographic order, but in a numeric sort 9 comes before 80.

換句話說,不傳比較函數時,sort 會先把元素轉成字串再比大小。看幾個例子:

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

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

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

所以 [10, 9, 80].sort() 會得到 [10, 80, 9]——這是初學者最常踩的坑。

自訂比較函數

function compareFunction(a, b) {
  if( a > b) {
    return -1;
  } else if(a < b) {
    return 1;
  } else {
    return 0;
  }
}
//Outputs ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction));

比較函數的回傳值規則是:

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

控制升降序

把方向參數用閉包帶進比較函數,就能動態切換:

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;
    }
  };
}
//Outputs ["1", "Benjamin", "zuojj"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction()));
//Outputs ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction("desc")));

undefined 與稀疏陣列的處理

MDN 提到 sort 的行為在 JavaScript 1.1 與 1.2 之間有過變化:

The behavior of the sort method changed between JavaScript 1.1 and JavaScript 1.2.

具體差異是:

In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.

In JavaScript 1.2, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array.

也就是說,undefined 會被排到陣列尾端。稀疏陣列的情況如下:

var arr = [];
arr[0] = "Ant";
arr[5] = "Zebra";
//Outputs ["Ant", 5: "Zebra"]
console.log(arr);
//Outputs 6
console.log(arr.length);
//Outputs "Ant*****Zebra"
console.log(arr.join("*"));

// 排序
var sortArr = arr.sort();
//Outputs ["Ant", "Zebra"]
console.log(sortArr);
//Outputs 6
console.log(sortArr.length);
//Outputs "Ant*Zebra****"
console.log(sortArr.join("*"));

排序後 "Zebra" 被移到索引 1,原本的空位則被壓到後方,但 length 依然是 6。這說明 sort 會搬動元素位置,卻不會自動縮短陣列。

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

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