TypedArray.prototype.sort()

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

sort() 方法用于对TypedArray 实例的元素进行就地排序,并返回对同一数组的引用。此方法具有与Array.prototype.sort() 相同的算法,不同之处在于它默认按数值而不是字符串对值进行排序。

试一试

const uint8 = new Uint8Array([40, 10, 50, 20, 30]);
uint8.sort();

console.log(uint8);
// Expected output: Uint8Array [10, 20, 30, 40, 50]

语法

js
sort()
sort(compareFn)

参数

compareFn 可选

一个用于确定元素顺序的函数。该函数将调用以下参数:

a

用于比较的第一个元素。

b

用于比较的第二个元素。

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

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

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

如果省略,则 TypedArray 元素将根据数值进行排序。

返回值

对原始 TypedArray 的引用,现已排序。请注意,TypedArray 是就地排序的,不会创建副本。

描述

有关更多详细信息,请参阅 Array.prototype.sort()。此方法不是通用的,只能在 TypedArray 实例上调用。

示例

使用 sort()

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

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 ]

规范

规范
ECMAScript® 2026 语言规范
# sec-%typedarray%.prototype.sort

浏览器兼容性

另见