TypedArray.prototype.toSorted()

TypedArray 实例的 toSorted() 方法是 sort() 方法的 copying 版本。它返回一个新的类型化数组,其中元素按升序排序。此方法与 Array.prototype.toSorted() 具有相同的算法,只不过它默认按数字而不是字符串对值进行排序。

¥The toSorted() method of TypedArray instances is the copying version of the sort() method. It returns a new typed array with the elements sorted in ascending order. This method has the same algorithm as Array.prototype.toSorted(), except that it sorts the values numerically instead of as strings by default.

语法

¥Syntax

js
toSorted()
toSorted(compareFn)

参数

¥Parameters

compareFn Optional

确定元素顺序的函数。如果省略,则类型化数组元素将根据数值排序。请参阅 sort() 了解更多信息。

返回值

¥Return value

一个新的类型化数组,其元素按升序排序。

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

描述

¥Description

详细信息请参见 Array.prototype.toSorted()。此方法不是通用的,只能在类型化数组实例上调用。

¥See Array.prototype.toSorted() for more details. This method is not generic and can only be called on typed array instances.

示例

¥Examples

对数组进行排序

¥Sorting an array

有关更多示例,另请参阅 Array.prototype.sort() 方法。

¥For more examples, see also the Array.prototype.sort() method.

js
const numbers = new Uint8Array([40, 1, 5, 200]);
const numberSorted = numbers.toSorted();
console.log(numberSorted); // Uint8Array [ 1, 5, 40, 200 ]
// Unlike plain Arrays, a compare function is not required
// to sort the numbers numerically.
console.log(numbers); // Uint8Array [ 40, 1, 5, 200 ]

规范

Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.tosorted

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看