我有以下功能:
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/