sort()方法如何在javascript中工作? [英] How does sort() method work in javascript?

查看:96
本文介绍了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.


这篇关于sort()方法如何在javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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