本文介绍了Array.sort()不能正确排序数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome 14和Firefox 5(尚未测试其他浏览器)中,以下代码未对数字进行正确排序:

In Chrome 14, and Firefox 5 (haven't tested other browsers), the following code doesn't sort the numbers correctly:

<script>
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);


document.write(a.sort())
</script>

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

It returns 10,100,20,30,60

我尝试了不同的数字,它总是表现为0不存在,否则正确排序数字。有谁知道为什么?

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

推荐答案

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

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

array.sort([compareFunction])

参数

compareFunction

compareFunction

指定定义排序顺序的函数。如果省略,则根据每个元素的字符串转换按字典顺序(按字典顺序)对数组进行排序。

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

在ECMAscript规范中(通用Javascript的规范性参考,,第15.4.4.11节,默认排序顺序是字典顺序,虽然它们没有出来并说出来,而是给出了一个概念排序函数的步骤,如果需要的话调用给定的比较函数,否则比较转换为字符串时的参数:

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return −1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

这篇关于Array.sort()不能正确排序数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 16:48
查看更多