This question already has answers here:
How to sort an array of integers correctly

(29个答案)


7年前关闭。




这似乎是一种简单的排序,但是JavaScript给出了错误的结果。
我做错什么了吗?还是这是一种语言怪癖?

最佳答案

Javascript按字母顺序排序。这意味着“10”低于“5”,因为“1”低于“5”。

要对数值进行排序,您需要像这样传递数值比较器:

function sorter(a, b) {
  if (a < b) return -1;  // any negative number works
  if (a > b) return 1;   // any positive number works
  return 0; // equal values MUST yield zero
}

[1,10, 5].sort(sorter);

或者,您可以通过传递更简单的功能来作弊:
function sorter(a, b){
  return a - b;
}

[1, 10, 5].sort(sorter);

此较短函数的逻辑是比较器必须返回x>0 if a > bx<0 if a < bzero if a is equal to b。所以如果你有
a=1 b=5
a-b will yield negative(-4) number meaning b is larger than a

a=5 b=1
a-b will yield positive number(4) meaning a is larger than b

a=3 b=3
a-b will yield 0 meaning they are equal

关于javascript - 为什么JavaScript无法排序[5,10,1]?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21019902/

10-17 03:01