如果你接觸javascript有一段時間了,你一定知道陣列排序函數sort,sort是array原型中的一個方法,即array.prototype.sort(),sort(compareFunction),其中compareFunction是比較函數,下面我們來看看來自Mozilla 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 ″ample, “8000 order, but in a numeric sort 9 comes before 80.
下面看些簡單的例子:
// Output ["a", "b", "c"]
console.log(["c", "b", "a"].sort());
// Output [1, 2, "a", "b"]
console.log(["b", 2, "a", 1].sort());
從上例可以看出,預設是依照字典中字母的順序來排序的。
幸運的是,sort接受一個自訂的比較函數,如下例:
排序完我們又有個疑問,如何控制升序和降序呢?
comparFunction的排序規則是這樣的:
1.If it returns a negative number, a will be sorted to a lower index in the array.
2.If it returns a positive number, a will be sorted to a higher index.
3.And if it returns 0 no sorting is necessary.
下面我們來看看摘自Mozilla MDN上的一段話:
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.詳情請戳這裡。
希望本文對你學習和了解sort()方法有幫助,文中不妥之處還望批評斧正。
參考連結:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort