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

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

推荐答案

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

是的

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

您可以通过以下方式找到自己:

You could find out your self with:

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天全站免登陆