javascript - coffeescript 排序不正确

标签 javascript coffeescript

这是我的脚本:

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/

相关文章:

coffeescript - 你如何在 Meteor 的客户端启动时使用全局 Coffeescript 变量?

javascript - 增加一个 div 数据值,然后在 coffeescript 中再次设置它

javascript - 是否可以向 DOM 文档添加方法?

javascript - 如何根据D3中的数据创建元素?

coffeescript - 如何使用 Leaflet 检查标记是否位于边界框中

javascript - Rails 应用程序中的 JQuery 插件 lightbox_me

javascript - jQuery 从 <a href 'Click Me' >Click Me</a> 中提取 ="http://example.com"

javascript - 使用 CSS 循环颜色过渡

javascript - Canvas 的 drawImage() 不进行子像素渲染/抗锯齿是否存在技术原因?

javascript - Google Analytics 是否具有用于长时间运行的 Web 应用程序的 "heartbeat"函数?