JavaScript的sort(compareFunction)如何工作? [英] How does JavaScript's sort (compareFunction) work?

查看:94
本文介绍了JavaScript的sort(compareFunction)如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var arr = [5, 2, 1, -10, 8];

arr.sort(function(a, b) {
  console.log(a,b)
  return b - a;

}) ; // 8, 5, 2, 1, -10

此回调如何工作?

选择a和b的原则是什么?

What is the principle of choice a and b?

请从内部解释此特定示例.

Please explain this particular example from the inside.

输出console.log(首先,请解释此输出):

output console.log (at first, please explain this output ):

  5 2
  2 1
  1 -10
 -10 8
  1 8
  2 8
  5 8

推荐答案

这取决于实现.这个实际的实施方式看起来像插入排序,但数据量很大(可能不同,例如使用Chrome,并且少于10个项目或更多项目的不同实现)从索引0到末尾,如果在最后两个项目之间未发生交换,则它会停止,否则会倒退到索引零.

It depends on the implementation. This actual implementation, looks like an insertion sort, with this amount of data (it could be different, like with Chrome, and the different implementation for less than 10 items or more items), is going from index zero to the end and if a swap has not taken place at the last two items, then it stops, otherwise it goes backwards to index zero.

基本上按此顺序进行测试和更改

Basically it tests and changes in this order

5   2   1 -10   8   original order
5   2
    2   1
        1 -10
          -10   8   swap
            8 -10
        1   8       swap
        8   1
    2   8           swap
    8   2
5   8               swap
8   5  2    1 -10   result

更复杂的排序可以更好地显示正在发生的事情,具有两个更大的值,需要将其移到数组的另一侧

A more complex sorting shows better what is going on, with two greater values, which need to move to the other side of the array

8   9   1   2   3   4   original array
8   9
    9   1               swap
    1   9
8   1                   swap
1   8
        9   2           swap
        2   9
    8   2               swap
    2   8
1   2
            9   3       swap
            3   9
        8   3           swap
        3   8
    2   3
                9   4   swap
                4   9
            8   4       swap
            4   8
        3   4
1   2   3   4   8   9   result

实时示例,并非在所有用户代理中都有效(例如,不是在Edge中,而是在Chrome中)

Live example, does not work in all user agents (eg not in Edge, but in Chrome)

var array = [8, 9, 1, 2, 3, 4];
console.log(JSON.stringify(array));
array.sort(function (a, b) {
    console.log(a , b, JSON.stringify(array));
    return a - b;
});
console.log(JSON.stringify(array));

.as-console-wrapper { max-height: 100% !important; top: 0; }

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

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