由于某种原因,排序未正确排序。为什么会这样?
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)
)
答案 0 :(得分:1)
要比较数字而不是字符串,比较功能可以简单地从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))