这是我的脚本:
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 ……
它可能与字符串与数字有关,但是“”将字符串强制转换为数字,无论如何,即使是字符串比较,结果也不是正确的排序.它似乎……随机.
解决方法:
作为@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.