← 中文资源

简体中文版本

比较器必须返回数字而不是布尔

布尔比较器只会产生 0 或 1,永远表达不了"更小",降序排列悄悄失效;用字段相减返回负数、零或正数,排序才真正生效,相等元素保持稳定。

阅读英文原文

运行结果

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

broken: [ 'ada:12', 'bo:9', 'cy:12' ]
fixed: [ 'ada:12', 'cy:12', 'bo:9' ]
tie order: [ 'ada', 'cy', 'bo' ]

实现说明

各个操作都建立在顶层绑定之上:scores、broken、byPointsDesc。

使用要点

  • 演示输出是带标签的(broken:、fixed:、tie order:),每个操作都会留下自己的一行标注。

常见问题

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

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

核心语句

const byPointsDesc = [...scores].sort((a, b) => b.points - a.points);
const broken = [...scores].sort((a, b) => a.points > b.points);

代码示例

const scores = [
  { name: "ada", points: 12 },
  { name: "bo", points: 9 },
  { name: "cy", points: 12 },
];

// A boolean comparator only ever yields 0 or 1: true reads as
// "a goes after b", false as "leave this pair alone", so no
// comparison ever signals "move a before b"
const broken = [...scores].sort((a, b) => a.points > b.points);
console.log("broken:", broken.map((s) => s.name + ":" + s.points)); // input order came back

// A comparator must return a number: negative, zero, or positive
const byPointsDesc = [...scores].sort((a, b) => b.points - a.points);
console.log("fixed:", byPointsDesc.map((s) => s.name + ":" + s.points));

// sort is stable since ES2019: ada and cy tie, ada keeps its lead
console.log("tie order:", byPointsDesc.map((s) => s.name));