Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
sort() 方法會*原地(in place)*對一個陣列的所有元素進行排序,並回傳此陣列。排序不一定是穩定的(stable)。預設的排序順序是根據字串的 Unicode 編碼位置(code points)而定。
由於依賴執行環境的實作,所以並不能保證排序的時間及空間複雜度。
指定一個函式來定義排序順序。假如省略此參數,陣列將根據各個元素轉為字串後的每一個字元之 Unicode 編碼位置值進行排序。
排序後的陣列。請注意此為原地(in place)進行排序過的陣列,並且不是原陣列的拷貝。
如果 compareFunction 沒有被應用,元素將被轉換為字串並以 Unicode 編碼位置進行比較來排序。舉例來說,"Banana" 會被排在 "cherry" 之前。在數值排序中,9 排在 80 前面,但因為數字被轉換成字串,在 Unicode 順序中 "80" 會在 "9" 的前面。
如果 compareFunction 被應用,陣列元素們將根據比較函式之回傳值來排序。如果 a 和 b 為被比較之兩元素,則:
所以,比較函式會是以下形式:
為了比較數字而不是字串,比較函式可以僅僅利用 a 減 b。以下函式將會升冪排序陣列:
sort 方法可以直接使用函式運算式(以及閉包(closures)):
物件可以按照其中一個屬性的值來排序。
下列範例建立了四個陣列並顯示其原本陣列內容、再進行排序。數字陣列先不使用比較函式(compare function)來排序,接著才依據比較函式進行排序。
這個範例將產生下列結果。就如結果所示,當使用比較函式時,數字會被正確的排序,不管是數字還是數字字串。
stringArray: Blue,Humpback,Beluga Sorted: Beluga,Blue,Humpback numberArray: 40,1,5,200 Sorted without a compare function: 1,200,40,5 Sorted with compareNumbers: 1,5,40,200 numericStringArray: 80,9,700 Sorted without a compare function: 700,80,9 Sorted with compareNumbers: 9,80,700 mixedNumericArray: 80,9,700,40,1,5,200 Sorted without a compare function: 1,200,40,5,700,80,9 Sorted with compareNumbers: 1,5,9,40,80,200,700為了排列非 ASCII 字元,即重音節字元(e、é、è、a、ä 等等),非英語字串:利用 String.localeCompare。此函式將比較這些字元,所以結果將會顯示正確的順序。
compareFunction 可以被陣列中的各個元素多次呼叫。依據 compareFunction 的特性,這將會產生大量運算。越多元素要排序 compareFunction 就越多工作要做,因此選擇使用 map 來排列也就是一個更明智的選擇。作法為先迭代陣列一次來取得排序時所需的值至暫時的陣列,並對此臨時陣列進行排序。然後再迭代臨時陣列來將正確順序之值放入原始陣列中。
| ECMAScript® 2027 Language Specification # sec-array.prototype.sort |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2025年7月14日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.