我发现使用排序而不使用比较函数会导致错误的答案,我不知道原因。
var a = [823564440,115438165,784484492,74243042,114807987,137522503,441282327,16531729,823378840,143542612]
a.sort()
a.sort((a,b) => a-b)
在我看来,两者应该给出相同的结果,但事实并非如此。显然后者是正确的。
a.sort()
[114807987, 115438165, 137522503, 143542612, 16531729, 441282327, 74243042, 784484492, 823378840, 823564440]
a.sort((a, b) => a-b)
[16531729, 74243042, 114807987, 115438165, 137522503, 143542612, 441282327, 784484492, 823378840, 823564440]
谁能告诉我这背后的原因?
根据 MDN documentation :
The sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. (Emphasis mine)†
由于您没有提供函数,因此使用默认排序顺序。因此,元素按照 字符串 进行排序,而后一种排序是根据数字值进行排序。
因此,1
在 2
之前,2
在 3
之前,等等。作为字符串的数字逐个比较。 (参见 list of unicode characters ;由于 Unicode 中的 1 是 U+0031,它位于 U+0032 之前,因此更小)。
在您的示例中,这意味着 115438165
出现在 74243042
之前,尽管后者在数学上更小。因为字符串是逐个比较的,所以 1
与 7
比较并且小于,从而产生结果。如需进一步阅读,请参阅 lexicographical order .
† 这是规范。查看ECMAScript® 2015 Language Specification ,第 22.1.3.24.1 节 - 运行时语义:SortCompare( x, y )
。此处解释了如果未传递排序函数,则比较 x
和 y
(使用 ToString
找到)的字符串表示形式。