sort()方法如何在javascript中工作?

sort()方法如何在javascript中工作?

问题描述:

我很困惑:

I am puzzled by this:

function min(a, b) {
  return b.length - a.length
}
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'].sort(min)-> array returns unchanged
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k','l'].sort(min) -> returns 
["f", "a", "c", "d", "e", "b", "g", "h", "i", "k", "l"]



问题是为什么?文档中没有任何内容。



我尝试过的事情:



我试图在MDN上查找带有字符串的方法的行为,但在这个问题上找不到任何东西。我在错误的位置查找了吗?


The question is why? There is nothing about it on the docs.

What I have tried:

I tried looking for behavior of the method with strings on MDN but could not find anything on this matter. Was I looking in a wrong place?

您的比较函数正在比较数组中字符串的长度。所有字符串都有一个字符,因此长度为 1 。这意味着比较函数认为所有字符串彼此相等。



查看文档:

Your comparison function is comparing the length of the strings in the array. All of the strings have a single character, so the length is 1. That means the comparison function considers all of the strings to be equal to each other.

Looking at the documentation:



排序不一定是稳定 [ ^ ]。


The sort is not necessarily stable[^].



换句话说,如果比较函数为源数组的两个元素返回相同的值,则无法保证元素将保持彼此相同的相对顺序。



您所看到的行为将根据数组的大小和正在使用的Javascript引擎而有所不同。输出是不可预测的。


In other words, if the comparison function returns the same value for two elements of the source array, there is no guarantee that the elements will remain in the same relative order to each other.

The behaviour you're seeing will vary depending on the size of the array, and the Javascript engine being used. The output is not predictable.