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

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

问题描述

以下代码如何将此数组按数字顺序排序?

How does the following code sort this array to be in numerical order?

var array=[25, 8, 7, 41]

array.sort(function(a,b){
  return a - b
})

我知道如果计算结果是......

I know that if the result of the computation is...

小于0 :a被排序为比b更低的索引。

零:a和b被视为相等,并且不执行排序。

大于0 :b被排序为比a更低的索引。

Less than 0: "a" is sorted to be a lower index than "b".
Zero: "a" and "b" are considered equal, and no sorting is performed.
Greater than 0: "b" is sorted to be a lower index than "a".

数组排序回调函数是否在多次调用期间被调用排序的过程?

Is the array sort callback function called many times during the course of the sort?

如果是这样,我想知道每次将哪两个数字传递给函数。我假设它首先取25(a)和8(b),然后是7(a)和41(b),所以:

If so, I'd like to know which two numbers are passed into the function each time. I assumed it first took "25"(a) and "8"(b), followed by "7"(a) and "41"(b), so:

25(a) - 8(b)= 17(大于零,所以将b排序为比a更低的索引):8,25

25(a) - 8(b) = 17 (greater than zero, so sort "b" to be a lower index than "a"): 8, 25

7(a) - 41(b)= -34(小于零,所以将a排序为比b更低的索引:7,41

7(a) - 41(b) = -34 (less than zero, so sort "a" to be a lower index than "b": 7, 41

这两组数字如何相互排序?

How are the two sets of numbers then sorted in relation to one another?

请帮助一个苦苦挣扎的新手!

Please help a struggling newbie!

推荐答案


在排序过程中多次调用数组排序回调函数?


如果是这样,我想知道每次将哪两个数字传递给函数

你可以找到你的自己:

array.sort((a,b) => {
  console.log(`comparing ${a},${b}`);
  return a > b ? 1
               : a === b ? 0 
                         : -1;
});

编辑

这是我得到的输出:

25,8
25,7
8,7
25,41

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

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