排序JavaScript数组的奇怪行为 [英] Weird behavior in sorting JavaScript array

查看:82
本文介绍了排序JavaScript数组的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试对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)返回1;否则if(a.length> b.length)返回-1;否则返回0; });  



在这种情况下正常工作让我回来数组。



控制台是这样的,





但当我尝试以下输入时,

  var arr = ['a','b','C','d','e','f', G,‘H’,‘I’,‘K’,L]; 

给我这个,





我无法弄清楚为什么会发生这种情况。



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

解决方案

< blockquote>

ECMAScript既没有规定特定的算法,也没有预期它是稳定的( Array.prototype.sort )。稳定的排序算法保持看起来相同的元素的相对顺序。 To Array#sort当比较函数返回0时,两个项目显示相同。虽然InsertionSort和MergeSort(Apple和Mozilla)是稳定的,但QuickSort(谷歌浏览器)不是(问题90)。如果数组中包含10个或更少的元素,Chrome将使用InsertionSort对数组进行排序。



因此Safari和Firefox将排序 [sed,dolor ,ipsum,foo,bar,cat,sit,man,lorem,amet,maecennas] (按字符长度)in一种sed将保留第一个位置的方式,而Chrome将掷骰子并且可能更喜欢cat来获得杆位。 Chrome开发人员显然喜欢小猫...


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



查看完整帖子这里


I encountered a strange behavior while trying to sort a JavaScript array.

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;
});

Works fine in this case giving me back the same array.

The console goes like this,

But when I try for this below input,

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

Gives me this,

I can't quite figure out why that is happening.

PS. I am writing this custom sort checking the length of the elements because I need an array that has its elements sorted according to the length.

解决方案

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…

So implementing a stable algorithm, such as MergeSort yourself, if you find yourself in need.

check the full post here

这篇关于排序JavaScript数组的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆