为什么points.sort(function(a,b){return a-b});返回-1,0或1? [英] Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?
问题描述
我的困难可能是我的数学文盲,但我试图在JavaScript数组中对某些数字进行排序,这是我在网上找到的解决方案。它确实有效,但我的问题是为什么?!我真的很想理解这段代码。
My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed work, but my question is why?! I would really like to understand this piece of code properly.
该网站,W3学校说:
你可以通过提供返回-1,0或1的函数来解决这个问题:
You can fix this by providing a function that returns -1, 0, or 1:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a,b){return a-b});
为什么只返回-1,0或1?我有谷歌搜索,返回可以返回你想要的任何值。
Why would only -1, 0 or 1 be returned? I have Googled, and return can return pretty much any value you want.
再次,如果这是一个令人难以置信的愚蠢问题我道歉。
Again, if this is an incredibly dumb question I apologise.
推荐答案
排序回调必须返回
- 如果
a< b
-
0
如果a === b
- 正数,如果
a> b
- a negative number if
a < b
0
ifa === b
- a positive number if
a > b
需要三个可能的返回值,因为sort函数现在需要 a
小于,等于或大于 b
,以便正确定位 a
在结果数组中。
Three possible return values are needed because the sort function needs to now whether a
is smaller than, equal to, or larger than b
in order to correctly position a
in the result array.
返回 -1
, 0
和 1
如果您使用的是非数字数据(我猜这就是为什么W3Schools会提到它)。但是如果你使用数值数据,你可以简单地减去这些值,因为
It is very common to just return -1
, 0
and 1
if you working with non-numerical data (I guess that's why W3Schools mentions it). But if you use numerical data, you can simply subtract the values because
- 如果
a< b
然后a - b< 0
,即负数 - 如果
a === b
则a - b === 0
,即0
- 如果
a> ; b
然后a - b> 0
,即正数
- if
a < b
thena - b < 0
, i.e. a negative number - if
a === b
thena - b === 0
, i.e.0
- if
a > b
thena - b > 0
, i.e. a positive number
W3Schools不是非常精确,这是你应该避免它的原因之一。使用 MDN 而不是。
W3Schools is not very precise which is one of the reason why you should avoid it. Use MDN instead.
这篇关于为什么points.sort(function(a,b){return a-b});返回-1,0或1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!