如何使用 Array.sort() 正确排序数字?

新手上路,请多包涵

在多个浏览器中,以下代码无法正确排序数字:

 a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
document.write(a.sort())

它返回 10,100,20,30,60

有人知道为什么吗?

原文由 Some Guy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 336
2 个回答

我尝试了不同的数字,它总是表现得好像 0 不存在一样,否则就会正确地对数字进行排序。有人知道为什么吗?

您将获得字典顺序排序(例如,将对象转换为字符串,并按字典顺序对它们进行排序),这是 Javascript 中的默认排序行为:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

>  array.sort([compareFunction])
>
> ```
>
> 参数
>
> 比较函数
>
> 指定定义排序顺序的函数。如果省略,数组将根据每个元素的字符串转换按字典顺序(按字典顺序)排序。

在 ECMAscript 规范(通用 Javascript 的规范参考)中, [ECMA-262,第 3 版。](http://www.ecma-international.org/publications/standards/Ecma-262-arch.htm) , section 15.4.4.11, default sort order is lexicographical, 虽然他们没有出来说出来,而是给出了概念排序函数的步骤,如果需要的话调用给定的比较函数,否则在转换为字符串时比较参数:

  1. If the argument comparefn is undefined, go to step 16.
  2. Call comparefn with arguments x and y.
  3. Return Result(14).
  4. Call ToString(x).
  5. Call ToString(y).
  6. If Result(16) < Result(17), return −1.
  7. If Result(16) > Result(17), return 1.
  8. Return +0.

”`

原文由 Jason S 发布,翻译遵循 CC BY-SA 4.0 许可协议

a.sort(function(a,b){return a - b})

这些可能令人困惑……请查看 此链接

原文由 Joseph Marikle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题