TypedArray.prototype.sort()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

TypedArray 实例的 sort() 方法对类型化数组 到位 的元素进行排序,并返回对同一类型化数组(现已排序)的引用。此方法与 Array.prototype.sort() 具有相同的算法,只不过它默认按数字而不是字符串对值进行排序。

¥The sort() method of TypedArray instances sorts the elements of a typed array in place and returns the reference to the same typed array, now sorted. This method has the same algorithm as Array.prototype.sort(), except that it sorts the values numerically instead of as strings by default.

Try it

语法

¥Syntax

js
sort()
sort(compareFn)

参数

¥Parameters

compareFn Optional

确定元素顺序的函数。使用以下参数调用该函数:

a

用于比较的第一个元素。

b

用于比较的第二个元素。

它应该返回一个数字,其中:

  • 负值表示 a 应位于 b 之前。
  • 正值表示 a 应位于 b 之后。
  • 零或 NaN 表示 ab 被视为相等。

为了记住这一点,请记住 (a, b) => a - b 按升序对数字进行排序。

如果省略,则类型化数组元素将根据数值排序。

返回值

¥Return value

对原始类型化数组的引用,现已排序。请注意,类型化数组按 到位 排序,并且不进行任何复制。

¥The reference to the original typed array, now sorted. Note that the typed array is sorted in place, and no copy is made.

描述

¥Description

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

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

示例

¥Examples

使用排序()

¥Using sort()

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

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

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

// Regular Arrays require a compare function to sort numerically:
numbers = [40, 1, 5, 200];
numbers.sort();
// [1, 200, 40, 5]

numbers.sort((a, b) => a - b); // compare numbers
// [ 1, 5, 40, 200 ]

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

¥Browser compatibility

也可以看看