gpt4 book ai didi

javascript - 在 javascript 中的 localeCompare 中排序

转载 作者:行者123 更新时间:2023-12-04 16:04:13 31 4
gpt4 key购买 nike

我正在编写如下所示的 Javascript 代码:

let arr = [
'1 Hello',
'2 Hello',
'3 Hello',
'4 Hello',
';1',
'z',
'%1',
'110 Hello',
'100 Hello',
'a',
'Z',
'00',
'21 Hello',
'9 Hello',
'13 Hello',
'10000 Hello',
'0 Hello',
'A'
];


arr.sort( (a, b) => {
return a.localeCompare(b, 'en', {
numeric: true
})
} ).forEach( ml => { console.log(ml) });


上面的 Javascript 正在打印以下 o/p:
;1
%1
00
0 Hello
1 Hello
2 Hello
3 Hello
4 Hello
9 Hello
13 Hello
21 Hello
100 Hello
110 Hello
10000 Hello
a
A
z
Z
=> undefined

问题陈述:

我想知道为什么在 o/p ;1即将到来 %1以及其他字符串如何在这里排序?

最佳答案

tldr;浏览器特定的实现。最近“标准化”了。
在我的回答中,我认为问题与 .sort() 无关。 JS 中的数组方法,但关于 .localeCompare() 的输出字符串方法。如果我们去MDN描述的方法https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare我们可以找到定义:

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.



以及规范的链接: https://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.localecompare .本规范有以下摘录:

When the localeCompare method is called with argument that, it returns a Number other than NaN that represents the result of a locale-sensitive String comparison of the this value (converted to a String) with that (converted to a String). The two Strings are S and That. The two Strings are compared in an implementation-defined fashion. The result is intended to order String values in the sort order specified by a host default locale...



您可以找到 Chromium 的“错误”报告“ localeCompare 实现不同于其他浏览器 ”: https://bugs.chromium.org/p/v8/issues/detail?id=459 , - 例如:
in v8 version 1.3.13.5, i get these results for the final sort:
A,R,Z,a,q,z,ä,æ

safari produces:
A,a,ä,æ,q,R,Z,z

firefox produces:
a,A,ä,æ,q,R,z,Z

one of the answers :

Marking as feature request as the current implementation does not violate the spec.



目前 AFAIK 用于比较 i18n Intl API使用规范。您可以在规范中找到有关比较规则的更多信息: https://www.ecma-international.org/ecma-402/2.0/#collator-objects .本文档也有关于比较选项的注释:

Unicode Technical Standard 35 describes ten locale extension keys that are relevant to collation: "co" for collator usage and specializations, "ka" for alternate handling, "kb" for backward second level weight, "kc" for case level, "kn" for numeric, "kh" for hiragana quaternary, "kk" for normalization, "kf" for case first, "kr" for reordering, "ks" for collation strength, and "vt" for variable top.



因此,您可以将输出调整到特定水平。我希望这会有所帮助,谢谢:)

关于javascript - 在 javascript 中的 localeCompare 中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52941016/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com