localecompare
This method compares a string to another, returning a number (negative, 0, positive) that tells if the current string is lower, equal or greater than the string passed as argument, according to the locale.
此方法将一个字符串与另一个字符串进行比较,返回一个数字(负数,0,正数),该数字指示当前字符串是小于,等于还是大于根据语言环境传递的字符串。
The locale is determined by the current locale, or you can pass it as a second argument:
语言环境由当前语言环境确定,或者您可以将其作为第二个参数传递:
'a'.localeCompare('à') //-1
'a'.localeCompare('à', 'it-IT') //-1
The most common use case is for ordering arrays:
最常见的用例是对数组进行排序:
['a', 'b', 'c', 'd'].sort((a, b) => a.localeCompare(b))
where one would typically use
人们通常会使用的地方
['a', 'b', 'c', 'd'].sort((a, b) => (a > b) ? 1 : -1)
with the difference that localeCompare()
allows us to make this compatible with alphabets used all over the globe.
区别在于localeCompare()
允许我们使其与全球使用的字母兼容。
An object passed as third argument can be used to pass additional options. Look for all the possible values of those options on MDN.
作为第三个参数传递的对象可用于传递其他选项。 在MDN上查找这些选项的所有可能值。
翻译自: https://flaviocopes.com/javascript-string-localecompare/
localecompare