没有比较功能的Javascript Array.prototype.sort()错误

标签 javascript

<分区>

我发现使用排序而不使用比较函数会导致错误的答案,我不知道原因。

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)†

由于您没有提供函数,因此使用默认排序顺序。因此,元素按照 字符串 进行排序,而后一种排序是根据数字值进行排序。

因此,12 之前,23 之前,等等。作为字符串的数字逐个比较。 (参见 list of unicode characters ;由于 Unicode 中的 1 是 U+0031,它位于 U+0032 之前,因此更小)。

在您的示例中,这意味着 115438165 出现在 74243042 之前,尽管后者在数学上更小。因为字符串是逐个比较的,所以 17 比较并且小于,从而产生结果。如需进一步阅读,请参阅 lexicographical order .


† 这是规范。查看ECMAScript® 2015 Language Specification第 22.1.3.24.1 节 - 运行时语义:SortCompare( x, y )。此处解释了如果未传递排序函数,则比较 xy(使用 ToString 找到)的字符串表示形式。

关于没有比较功能的Javascript Array.prototype.sort()错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41092283/

相关文章:

javascript - arr.push(arr.splice(n,1)) "swallows"被移动对象的属性

javascript - 使用 getElementById 一次指定 2 个操作

javascript - 导出提供者函数和附着对象

javascript - (JavaScript/HTML) 如何更改按钮单击时样式属性的显示?

javascript - 路由在 Angular js 中无法正常工作

javascript - 在 aspx 输入字段上/中插入文本并设置焦点?

javascript - 我怎样才能得到数组的真实计数?

javascript - .click/.on ('click' 内的 IF 语句不起作用

javascript - 使用 Passport.js 的登录系统始终执行 “failureRedirect” (nodejs)

javascript - AngularJS ng-options 默认选择的选项