Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. Array
  6. Array.prototype.toSorted()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

Array.prototype.toSorted()

Baseline 2023
Newly available

Since ⁨July 2023⁩, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Array 实例的toSorted() 方法是sort() 方法的复制方法版本。它返回一个新数组,其元素按升序排列。

语法

js
// 不传入函数toSorted()// 传入箭头函数toSorted((a, b) => { /* … */ })// 传入比较函数toSorted(compareFn)// 內联比较函数toSorted(function compareFn(a, b) { /* … */ })

参数

compareFn可选

指定一个定义排序顺序的函数。如果省略,则将数组元素转换为字符串,然后根据每个字符的 Unicode 码位值进行排序。

a

用于比较的第一个元素。

b

用于比较的第二个元素。

返回值

一个新数组,其元素按升序排序。

描述

有关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() 方法会读取thislength 属性。然后它会收集所有在0length - 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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp