TypedArray.prototype.sort()
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之后。 - 零或
NaN表示a和b被视为相等。
要记住这一点,请记住
(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 |
浏览器兼容性
加载中…