← 中文资源

简体中文版本

TypedArray.sort 按数值比较而不是字符串

Array.sort 默认按字符串比较,9 会排在 80 与 700 之后;TypedArray.sort 直接按数值比较并原地排序,返回同一视图,仍可传 comparator 改成降序。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

array sort : 700,80,9
typed sort : 9,80,700
typed desc : 700,80,9
same object: true

实现说明

各个操作都建立在顶层绑定之上:plain、typed。

使用要点

  • 跑完文件,输出里会留下标记——array sort :、typed sort :、typed desc :。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 跨调用保留的状态放在这些顶层绑定里:plain、typed。

核心语句

const typed = Float64Array.from(plain);
const plain = [9, 80, 700];

代码示例

// Regular Array.sort compares as STRINGS by default; TypedArray.sort
// compares numerically, because every element is already a number
const plain = [9, 80, 700];
console.log('array sort :', plain.sort().join(','));

const typed = Float64Array.from(plain);
console.log('typed sort :', typed.sort().join(','));

// TypedArray.sort accepts a comparator too, e.g. descending
console.log('typed desc :', typed.sort((a, b) => b - a).join(','));

// It mutates in place and returns the same view, like Array.sort
console.log('same object:', typed.sort() === typed);