gpt4 book ai didi

javascript - 为什么浏览器按以下方式排序

转载 作者:行者123 更新时间:2023-11-30 15:34:48 26 4
gpt4 key购买 nike

我有以下功能:

var sortString = function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return 1;
if (a > b) return -1;
return 0;
}

我有以下两个字符串:

x = ["B1C3N_EUR_DFAK_ALL_3M_ALL","B1C3N_EUR_BPP_BCO_3M"];

当我在此数组上运行上述函数时。我希望“B1C3N_EUR_BPP_BCO_3M”位于索引 0,而浏览器以相反的顺序返回它。我已经检查了 Chrome 和 IE。为什么会这样??

我是否需要用其他值替换“-”。有什么办法可以不用更换就可以做到吗。

最佳答案

您在 Array#sort 的回调中为更小和更大的值返回了错误的值.

if (a < b) return 1;
// ^ should be -1, because a is smaller than b

if (a > b) return -1;
// ^^ should be 1, because a is greater than b

要获得更简洁的样式,您可以使用 String#localeCompare ,它测试给定的字符串并返回所需范围内的值。

关于javascript - 为什么浏览器按以下方式排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719684/

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