Intl.Collator
Intl.Collator 对象支持区分语言的字符串比较。
试一试
console.log(["Z", "a", "z", "ä"].sort(new Intl.Collator("de").compare));
// Expected output: Array ["a", "ä", "z", "Z"]
console.log(["Z", "a", "z", "ä"].sort(new Intl.Collator("sv").compare));
// Expected output: Array ["a", "z", "Z", "ä"]
console.log(
["Z", "a", "z", "ä"].sort(
new Intl.Collator("de", { caseFirst: "upper" }).compare,
),
);
// Expected output: Array ["a", "ä", "Z", "z"]
构造函数
Intl.Collator()-
创建一个新的
Collator对象。
静态方法
Intl.Collator.supportedLocalesOf()-
返回一个数组,其中包含提供的区域设置中受支持的那些区域设置,而无需回退到运行时默认区域设置。
实例属性
这些属性定义在 Intl.Collator.prototype 上,并被所有 Intl.Collator 实例共享。
Intl.Collator.prototype.constructor-
创建了实例对象的构造函数。对于
Intl.Collator实例,初始值为Intl.Collator构造函数。 Intl.Collator.prototype[Symbol.toStringTag]-
[Symbol.toStringTag]属性的初始值为字符串"Intl.Collator"。此属性用于Object.prototype.toString()。
实例方法
Intl.Collator.prototype.compare()-
Getter 函数,根据此
Intl.Collator对象的排序顺序比较两个字符串。 Intl.Collator.prototype.resolvedOptions()-
返回一个新的对象,其中包含在对象初始化期间计算出的区域设置和排序选项。
示例
使用 Collator
以下示例演示了一个字符串在另一个字符串之前、之后或同等位置的不同潜在结果
js
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
请注意,上面代码中显示的结果可能因浏览器和浏览器版本而异。这是因为这些值是实现特定的。也就是说,规范只要求“之前”和“之后”的值分别为负数和正数。
使用语言环境
由 Intl.Collator.prototype.compare() 提供的结果因语言而异。为了获得应用程序用户界面所用语言的排序顺序,请确保使用 locales 参数指定该语言(以及可能的备用语言)。
js
// in German, ä sorts with a
console.log(new Intl.Collator("de").compare("ä", "z"));
// -1, or some other negative value
// in Swedish, ä sorts after z
console.log(new Intl.Collator("sv").compare("ä", "z"));
// 1, or some other positive value
使用选项
由 Intl.Collator.prototype.compare() 提供的结果可以使用 options 参数进行自定义。
js
// in German, ä has a as the base letter
console.log(new Intl.Collator("de", { sensitivity: "base" }).compare("ä", "a"));
// 0
// in Swedish, ä and a are separate base letters
console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a"));
// 1, or some other positive value
规范
| 规范 |
|---|
| ECMAScript® 2026 国际化 API 规范 # collator-objects |
浏览器兼容性
加载中…