Intl.Collator.prototype.compare()

Intl.Collator 实例的 compare() 方法根据此 collator 对象的排序顺序比较两个字符串。

¥The compare() method of Intl.Collator instances compares two strings according to the sort order of this collator object.

Try it

语法

¥Syntax

js
compare(string1, string2)

参数

¥Parameters

string1string2

要相互比较的字符串。

返回值

¥Return value

一个数字,指示 string1string2 如何根据 Intl.Collator 对象的排序顺序相互比较:

¥A number indicating how string1 and string2 compare to each other according to the sort order of this Intl.Collator object:

  • 如果 string1string2 之前,则为负值;
  • 如果 string1string2 之后,则为正值;
  • 如果认为它们相等,则为 0。

示例

¥Examples

使用比较进行数组排序

¥Using compare for array sort

使用 compare 函数对数组进行排序。请注意,该函数绑定到从中获取它的整理器,因此它可以直接传递给 Array.prototype.sort()

¥Use the compare function for sorting arrays. Note that the function is bound to the collator from which it was obtained, so it can be passed directly to Array.prototype.sort().

js
const a = ["Offenbach", "Österreich", "Odenwald"];
const collator = new Intl.Collator("de-u-co-phonebk");
a.sort(collator.compare);
console.log(a.join(", ")); // "Odenwald, Österreich, Offenbach"

使用比较进行数组搜索

¥Using compare for array search

使用 compare 函数在数组中查找匹配字符串:

¥Use the compare function for finding matching strings in arrays:

js
const a = ["Congrès", "congres", "Assemblée", "poisson"];
const collator = new Intl.Collator("fr", {
  usage: "search",
  sensitivity: "base",
});
const s = "congres";
const matches = a.filter((v) => collator.compare(v, s) === 0);
console.log(matches.join(", ")); // "Congrès, congres"

规范

Specification
ECMAScript Internationalization API Specification
# sec-intl.collator.prototype.compare

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看