javascript - 排序 JavaScript 数组时的奇怪行为

标签 javascript arrays sorting

<分区>

我在尝试对 JavaScript 数组进行排序时遇到了一个奇怪的行为。

var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k'];

arr.sort(function (a, b) {
  console.log(a, b);
  if (a.length < b.length) return 1;
  else if (a.length > b.length) return -1;
  else return 0;
});

在这种情况下工作正常,返回相同的数组。

控制台是这样的,

enter image description here

但是当我尝试下面的输入时,

var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k', 'l'];

给我这个,

enter image description here

我不太明白为什么会这样。

附言。我正在编写此自定义排序检查元素的长度,因为我需要一个其元素根据长度排序的数组。

最佳答案

ECMAScript neither dictates a specific algorithm, nor expects it to be stable (Array.prototype.sort). Stable sorting algorithms maintain the relative order of elements that appear to be "the same". To Array#sort two items appear the same when the comparison function returns 0. While InsertionSort and MergeSort (Apple and Mozilla) are stable, QuickSort (Google Chrome) is not (Issue 90). Chrome will sort arrays using InsertionSort if the array has 10 or less elements.

So Safari and Firefox will sort ["sed", "dolor", "ipsum", "foo", "bar", "cat", "sit", "man", "lorem", "amet", "maecennas"] (by character length) in a way that "sed" will retain first position, while Chrome will roll the dice and possibly prefer "cat" to take the pole position. The Chrome developers obviously like Kittens…

因此,如果您发现自己有需要,请自己实现一个稳定的算法,例如 MergeSort。

查看完整帖子 here

关于javascript - 排序 JavaScript 数组时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529668/

相关文章:

javascript - Facebook 如何在 AJAX 页面加载期间显示浏览器加载进度?

javascript - Quickblox 通过 Raspberry Pi 3 上的 UWP 应用程序

c++ - 你能在 C++ 中使用 'new' 模拟动态数组大小吗?

ruby - 解释简洁的 ruby​​ 'nil' 错误

c - 在 c 中按字典顺序打印 trie

javascript - 带连字符的 YouTube 网址测试器

javascript - 无法使用 jquery 删除 CSS `position` 属性

c - malloc() 导致循环中取消引用的二维字符数组崩溃

java - 如何旋转数组?

java - 用于计算未正确输出的算法的比较和执行时间的代码