此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Array.prototype.toSorted()
Baseline 2023Newly available
Since July 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
In this article
语法
js
// 不传入函数toSorted()// 传入箭头函数toSorted((a, b) => { /* … */ })// 传入比较函数toSorted(compareFn)// 內联比较函数toSorted(function compareFn(a, b) { /* … */ })参数
compareFn可选指定一个定义排序顺序的函数。如果省略,则将数组元素转换为字符串,然后根据每个字符的 Unicode 码位值进行排序。
返回值
一个新数组,其元素按升序排序。
描述
有关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,};console.log(Array.prototype.toSorted.call(arrayLike));// [4, 5, undefined]规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.tosorted> |