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() 方法的 copying 版本。它返回一个新数组,其中元素按升序排序。

¥The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.

语法

¥Syntax

js
toSorted()
toSorted(compareFn)

参数

¥Parameters

compareFn Optional

确定元素顺序的函数。如果省略,数组元素将转换为字符串,然后根据每个字符的 Unicode 代码点值进行排序。请参阅 sort() 了解更多信息。

返回值

¥Return value

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

¥A new array with the elements sorted in ascending order.

描述

¥Description

有关 compareFn 参数的更多信息,请参阅 sort()

¥See sort() for more information on the compareFn parameter.

当在 稀疏数组 上使用时,toSorted() 方法会迭代空槽,就好像它们具有值 undefined 一样。

¥When used on sparse arrays, the toSorted() method iterates empty slots as if they have the value undefined.

toSorted() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。

¥The toSorted() method is generic. It only expects the this value to have a length property and integer-keyed properties.

示例

¥Examples

对数组进行排序

¥Sorting an array

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()

¥For more usage examples, see sort().

在稀疏数组上使用 toSorted()

¥Using toSorted() on sparse arrays

空槽按其值为 undefined 进行排序。它们总是被排序到数组的末尾,并且不会为它们调用 compareFn

¥Empty slots are sorted as if they have the value undefined. They are always sorted to the end of the array and compareFn is not called for them.

js
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]

对非数组对象调用 toSorted()

¥Calling toSorted() on non-array objects

toSorted() 方法读取 thislength 属性。然后,它收集 0length - 1 范围内的所有现有整数键控属性,对它们进行排序,并将它们写入新数组。

¥The toSorted() method reads the length property of this. It then collects all existing integer-keyed properties in the range of 0 to length - 1, sorts them, and writes them into a new array.

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]

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.tosorted

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看