← 中文资源

简体中文版本

localeCompare 按区域规则排序

localeCompare 与 Intl.Collator 按语言规则排序:numeric 修复 img10 排在 img2 前的字典序缺陷,sensitivity 决定大小写与变音符号是否参与。

阅读英文原文

运行结果

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

[ 'img1.png', 'img10.png', 'img2.png' ]
[ 'img1.png', 'img2.png', 'img10.png' ]
[ 'img1.png', 'img2.png', 'img10.png' ]
accent sorts -1
[ 'adam', 'Zoe', 'Åke' ]

实现说明

演示用的数据放在这几个模块级绑定中:files、coll、ci、names。

使用要点

  • 跑完文件,输出里会留下标记——cafe。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 状态都挂在模块顶层:files、coll、ci。

核心语句

const coll = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
const ci = new Intl.Collator("en", { sensitivity: "accent" });

代码示例

const files = ["img10.png", "img2.png", "img1.png"];

// 默认字典序:字典序把 "10" 排在 "2" 前
console.log([...files].sort());

// numeric: true 按数值比较内嵌数字
console.log([...files].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));

// Intl.Collator 复用比较器,批量排序更快
const coll = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
console.log([...files].sort((a, b) => coll.compare(a, b)));

// sensitivity 控制大小写/变音符号是否影响排序
const ci = new Intl.Collator("en", { sensitivity: "accent" });
console.log("cafe" < "café" ? "accent sorts" : "base equal",
  ci.compare("cafe", "café"));

// localeCompare 返回 -1/0/1 形态,可直接做比较器
const names = ["Zoe", "adam", "Åke"];
console.log([...names].sort((a, b) => a.localeCompare(b, "sv")));