数字排序数组返回无效结果

时间:2018-10-04 12:42:36

标签: javascript

由于某种原因,排序未正确排序。为什么会这样?

console.log(
  [0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0].sort((a,b)=>a<b)
)

但是反函数起作用。...

console.log(
  [0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0].sort((a,b)=>a>b)
)

2 个答案:

答案 0 :(得分:1)

Array.prototype.sort()

  

要比较数字而不是字符串,比较功能可以简单地从a中减去b。

以下函数将对数组升序排序(如果它不包含Infinity和NaN):

console.log(
 [0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0].sort((a,b)=>a - b)
)

答案 1 :(得分:0)

函数应该为a-b返回ascending或为b-a返回descending

console.log([0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0,5].sort((a,b) => a - b)) 

console.log([0,0,0,0,1,0,0,0,3,0,0,0,0,0,1,1,0,2,1,1,0,0,0,0,0,0,5].sort((a,b) => b - a))