gpt4 book ai didi

javascript - localeCompare区分大小写的字母顺序问题

转载 作者:行者123 更新时间:2023-12-04 03:42:07 25 4
gpt4 key购买 nike

我正在尝试在这里实现 aAbBcC。我尝试了 en-US 希望得到想要的结果。在“Acuityads”之前期待“alpha”。

var array = [{name:"Acuityads"},{name:"alpha"}];

console.log(array.sort(function(a,b){return a.name.localeCompare(b.name,
'en-US-u-kf-lower'); }));


console.log(array.sort(function(a,b){return a.name.localeCompare(b.name,
'en-US'); }));

"alpha".localeCompare("Acuityads", 'en-US') // output as 1

最佳答案

讨论 in the comments ,这看起来像是规范或 vendor 实现中的不一致。
an earlier question on the same topic没有任何我很乐意接受的答案,这里是 a manual implementation :

const input = ["aaaaa", "aaa", "aa", "aaaa", "aA", "Aa", "AA", "ab", "aB", "Ab", "AB"];

function caseSensitiveCompare(a, b) {
// Sort character by character, return early if possible
for (let ii = 0; ii < Math.max(a.length, b.length); ii++) {
const aChar = a.charAt(ii);
const bChar = b.charAt(ii);

// If inputs match up to here, but lengths don't match, sort by length
if (!(aChar && bChar)) {
return a.length - b.length;
}

// If we meet a differing character, return early
const comp = aChar.localeCompare(bChar);
if (comp !== 0) {
return comp;
}
}
// If we found nothing to do, the strings are equal
return 0;
}

console.log(input.sort(caseSensitiveCompare));

关于javascript - localeCompare区分大小写的字母顺序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65842776/

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