語法
js
toSorted()
toSorted(compareFn)
引數
compareFn可選-
一個用於確定元素順序的函式。如果省略,陣列元素將被轉換為字串,然後根據每個字元的 Unicode 碼點值進行排序。有關更多資訊,請參閱
sort()。
返回值
一個包含升序排序元素的新陣列。
描述
有關 compareFn 引數的更多資訊,請參閱 sort()。
在 稀疏陣列 上使用時,toSorted() 方法會將空槽視作 undefined 值進行迭代。
toSorted() 方法是 通用 的。它只要求 this 值具有 length 屬性和整數鍵屬性。
示例
對陣列進行排序
js
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']
const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]
有關更多使用示例,請參閱 sort()。
在稀疏陣列上使用 toSorted()
空槽被視為 undefined 值進行排序。它們始終被排序到陣列的末尾,並且不會為它們呼叫 compareFn。
js
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]
在非陣列物件上呼叫 toSorted()
toSorted() 方法讀取 this 的 length 屬性。然後,它會收集 0 到 length - 1 範圍內的所有現有整數鍵屬性,對它們進行排序,然後將它們寫入一個新陣列。
js
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
3: 3, // ignored by toSorted() since length is 3
};
console.log(Array.prototype.toSorted.call(arrayLike));
// [4, 5, undefined]
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.tosorted |
瀏覽器相容性
載入中…