String.prototype.localeCompare()

String 值的 localeCompare() 方法返回一个数字,指示该字符串在排序顺序中是位于给定字符串之前、之后还是相同。在支持 Intl.Collator API 的实现中,此方法只需调用 Intl.Collator

¥The localeCompare() method of String values returns a number indicating whether this string comes before, or after, or is the same as the given string in sort order. In implementations with Intl.Collator API support, this method simply calls Intl.Collator.

当比较大量字符串时,例如对大型数组进行排序时,最好创建一个 Intl.Collator 对象并使用其 compare() 方法提供的功能。

¥When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare() method.

Try it

语法

¥Syntax

js
localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)

参数

¥Parameters

localesoptions 参数自定义函数的行为,并让应用指定应使用其格式约定的语言。

¥The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

在支持 Intl.Collator API 的实现中,这些参数与 Intl.Collator() 构造函数的参数完全对应。不支持 Intl.Collator 的实现被要求忽略这两个参数,使得返回的比较结果完全依赖于实现 - 只需要一致。

¥In implementations that support the Intl.Collator API, these parameters correspond exactly to the Intl.Collator() constructor's parameters. Implementations without Intl.Collator support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be consistent.

compareString

referenceStr 进行比较的字符串。所有值都是 强制为字符串,因此省略它或传递 undefined 会导致 localeCompare() 与字符串 "undefined" 进行比较,这很少是你想要的。

locales Optional

带有 BCP 47 语言标记的字符串,或此类字符串的数组。对应于 Intl.Collator() 构造函数的 locales 参数。

在不支持 Intl.Collator 的实现中,该参数被忽略,通常使用主机的区域设置。

options Optional

调整输出格式的对象。对应于 Intl.Collator() 构造函数的 options 参数。

在不支持 Intl.Collator 的实现中,该参数被忽略。

有关 localesoptions 参数及其使用方法的详细信息,请参阅 Intl.Collator() constructor

¥See the Intl.Collator() constructor for details on the locales and options parameters and how to use them.

返回值

¥Return value

如果 referenceStr 出现在 compareString 之前,则为负数;如果 referenceStr 发生在 compareString 之后,则为正;0(如果它们相等)。

¥A negative number if referenceStr occurs before compareString; positive if the referenceStr occurs after compareString; 0 if they are equivalent.

Intl.Collator 的实现中,这相当于 new Intl.Collator(locales, options).compare(referenceStr, compareString)

¥In implementations with Intl.Collator, this is equivalent to new Intl.Collator(locales, options).compare(referenceStr, compareString).

描述

¥Description

返回一个整数,指示 referenceStr 是否位于 compareString 之前、之后或等于 compareString

¥Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareString.

  • referenceStr 出现在 compareString 之前时为负
  • referenceStrcompareString 之后发生时为正
  • 如果相等则返回 0

警告:不要依赖 -11 的精确返回值!

¥Warning: Do not rely on exact return values of -1 or 1!

负整数和正整数结果在浏览器之间(以及浏览器版本之间)有所不同,因为 ECMAScript 规范仅强制要求使用负值和正值。某些浏览器可能会返回 -22,甚至其他一些负值或正值。

¥Negative and positive integer results vary between browsers (as well as between browser versions) because the ECMAScript specification only mandates negative and positive values. Some browsers may return -2 or 2, or even some other negative or positive value.

示例

¥Examples

使用 localeCompare()

¥Using localeCompare()

js
// The letter "a" is before "c" yielding a negative value
"a".localeCompare("c"); // -2 or -1 (or some other negative value)

// Alphabetically the word "check" comes after "against" yielding a positive value
"check".localeCompare("against"); // 2 or 1 (or some other positive value)

// "a" and "a" are equivalent yielding a neutral value of zero
"a".localeCompare("a"); // 0

对数组进行排序

¥Sort an array

localeCompare() 启用数组不区分大小写的排序。

¥localeCompare() enables case-insensitive sorting for an array.

js
const items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"];
items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']

检查浏览器对扩展参数的支持

¥Check browser support for extended arguments

并非所有浏览器都支持 localesoptions 参数。

¥The locales and options arguments are not supported in all browsers yet.

要检查实现是否支持它们,请使用 "i" 参数(拒绝非法语言标记的要求)并查找 RangeError 异常:

¥To check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a RangeError exception:

js
function localeCompareSupportsLocales() {
  try {
    "foo".localeCompare("bar", "i");
  } catch (e) {
    return e.name === "RangeError";
  }
  return false;
}

使用语言环境

¥Using locales

localeCompare() 提供的结果因语言而异。为了获取应用用户界面中使用的语言的排序顺序,请确保使用 locales 参数指定该语言(可能还有一些后备语言):

¥The results provided by localeCompare() vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

js
console.log("ä".localeCompare("z", "de")); // a negative value: in German, ä sorts before z
console.log("ä".localeCompare("z", "sv")); // a positive value: in Swedish, ä sorts after z

使用选项

¥Using options

可以使用 options 参数自定义 localeCompare() 提供的结果:

¥The results provided by localeCompare() can be customized using the options argument:

js
// in German, ä has a as the base letter
console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0

// in Swedish, ä and a are separate base letters
console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // a positive value

数字排序

¥Numeric sorting

js
// by default, "2" > "10"
console.log("2".localeCompare("10")); // 1

// numeric using options:
console.log("2".localeCompare("10", undefined, { numeric: true })); // -1

// numeric using locales tag:
console.log("2".localeCompare("10", "en-u-kn-true")); // -1

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.localecompare
ECMAScript Internationalization API Specification
# sup-String.prototype.localeCompare

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also