JavaScript 排序顺序错误

javascript sort in wrong order

本文关键字:错误 顺序 排序 JavaScript      更新时间:2023-09-26

我在javascript(node.js)排序函数没有一直以正确的顺序排序时遇到问题。我需要它对负数和正数进行排序,并首先返回最小的非负数。这是我现在使用的:

.sort(function(a, b){if(a >= 0){return a - b;}else{return 1;}});

但是,当只有一个正数,并且它经常发生在末尾时,该数字被排序为倒数第二。我可以得到一些更好的方法来实现这一点吗?

此排序函数之所以有效,是因为仅当ab 位于 0 的同一侧时,它才会对数字进行排序:

function SortNonNegativesFirst(a,b){
    if((a>=0) == (b>=0)) // Checks if both numbers are on the same side of zero
        return a-b;
    return a<b; // One is negative, one is positive, so return whether a is negative
}
console.log([1,6,8,4,-3,5,-2,3].sort(SortNonNegativesFirst)); //[1, 3, 4, 5, 6, 8, -3, -2]

下面是使用三元运算符的一种方法:

alert([8,5,-1,-8,-2,7,1,10,1,7,-3].sort(function(a,b) {
  return a*b < 0 ? b : a-b;
}));

三元运算符是if ... else的快捷方式,所以上面相当于写:

alert([8,5,-1,-8,-2,7,1,10,1,7,-3].sort(function(a,b) {
  if(a*b < 0) return b;
  else return a-b;
}));

如果ab具有不同的符号(正号和负号),则此代码返回 true:

if(a*b < 0) return b;

如果b为正,sort将其放在负a之前。 如果b为负数,sort将其放在正a之后