这是我的脚本:
alert("why isn't this sorted right? #{["6","7","2","11","10","9","4","5","3","8","1"].sort
(a,b) -> +a < +b }")
您可以尝试运行它here .
结果将是:
why isn't this sorted right? 9,6,8,11,10,7,5,4,3,2,1
我的问题是,为什么?我希望答案是 11, 10, 9, 8, ....
它可能与字符串 vs 数字有关,但“+”将字符串强制转换为数字,无论如何,即使是字符串比较,结果也不是正确的排序。这似乎..随机。
最佳答案
作为@Keith commented ,问题不在于 Coffeescript,而在于滥用 Array::sort
接受的比较函数。
alert(
"In order to work, a comparator must return -1, 1 or 0 #{
["6","7","2","11","10","9","4","5","3","8","1"].sort(
(a, b) -> +b - +a
)}"
)
Array.prototoype.sort
documentation .
运行它 here .
关于javascript - coffeescript 排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40076207/