JavaScript错误的顺序sorting

我遇到了一个javascript(node.js)sorting函数没有按照正确的顺序sorting的问题。 我需要它通过负数和正数进行sorting,并首先返回最小的非负数。 这就是我现在使用的:

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

但是,如果只有一个正数,并且在最后经常发生的情况下,则该数字按倒数第二sorting。 我可以通过更好的方式来实现这一点吗?

这里有一个使用三元运算符的方法:

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

这个sortingfunction的工作原理是因为它只对数字进行sorting,如果a位于0的同一边,就像b

 function SortNonNegativesFirst(a,b){ if((a>=0) == (b>=0)) // Checks if both numbers are on the same side of zero return ab; 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]