实现说明
各个操作都建立在顶层绑定之上: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));