javascript 为什么 points.sort(function(a, b){return ab}); 返回 -1、0 还是 1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24768492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?
提问by Camarellini Viberg
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.
我在这里的困难可能是我的数学文盲,但我试图对 JavaScript 数组中的一些数字进行排序,这是我在网上找到的解决方案。它确实有效,但我的问题是为什么?!我真的很想正确理解这段代码。
The site, W3 Schools says:
该网站,W3 Schools 说:
You can fix this by providing a function that returns -1, 0, or 1:
您可以通过提供返回 -1、0 或 1 的函数来解决此问题:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a,b){return a-b});
Why would only -1, 0 or 1 be returned? I have Googled, and return can return pretty much any value you want.
为什么只返回 -1、0 或 1?我用谷歌搜索过,返回几乎可以返回任何你想要的值。
Again, if this is an incredibly dumb question I apologise.
再次,如果这是一个非常愚蠢的问题,我深表歉意。
回答by Felix Kling
The sort callback has to return
排序回调必须返回
- a negative number if
a < b
0
ifa === b
- a positive number if
a > b
- 一个负数,如果
a < b
0
如果a === b
- 一个正数,如果
a > b
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.
需要三个可能的返回值,因为排序函数现在需要判断a
是小于、等于还是大于b
,以便a
在结果数组中正确定位。
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
这是刚刚回归很常见的-1
,0
而且1
如果你用非数值数据的工作(我想这就是为什么W3Schools的提到它)。但是如果你使用数字数据,你可以简单地减去这些值,因为
- 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
- 如果
a < b
那么a - b < 0
,即负数 - 如果
a === b
那么a - b === 0
,即0
- 如果
a > b
然后a - b > 0
,即一个正数
W3Schools is not very precise which is one of the reason why you should avoid it. Use MDNinstead.
W3Schools 不是很精确,这也是您应该避免使用它的原因之一。请改用MDN。
回答by Alireza
It is not bound to be -1, 0, 1 any negative or positive number will do the trick.
它不一定是 -1, 0, 1 任何负数或正数都可以。
But how it works? The sort() method needs to know the relation between each two elements in order to sort them. For each pair (according to the algorithm used) it calls the function then based on the return value, may swap them. Note that a-b
returns a negative value if b>a
and a positive one if a>b
. That leads to an ascending order.
但它是如何工作的?sort() 方法需要知道每两个元素之间的关系才能对它们进行排序。对于每一对(根据使用的算法),它调用函数然后根据返回值,可以交换它们。请注意,a-b
返回负值 ifb>a
和正值 if a>b
。这导致升序。
Just for test, replace a-b
with b-a
and you will get a descending order. You may even make it more complicated, sort them based on (for example) their least significant digit:
只是为了测试,替换a-b
为b-a
,你会得到一个降序。你甚至可以让它更复杂,根据(例如)它们的最低有效数字对它们进行排序:
a.sort(function() {return (a%10) - (b%10);}
回答by Mitul Panchal
If Function(a, b)
is less than 0, sort a
to an index lower than b
, i.e. a
comes first.
如果Function(a, b)
小于 0,则排序a
到小于的索引b
,即排a
在第一位。
If Function(a, b)
returns 0, leave a
and b
unchanged with respect to each other, but sorted with respect to all different elements.
如果Function(a, b)
返回0,休假a
和b
相对于彼此不变,但对于所有不同的元素进行排序。
Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
注意:ECMAscript 标准不保证这种行为,因此并非所有浏览器(例如至少可以追溯到 2003 年的 Mozilla 版本)都尊重这一点。
If Function(a, b)
is greater than 0, sort b
to an index lower than a
, i.e. b
comes first.
Function(a, b)
must always return the same value when given a specific pair of elements a
and b
as its two arguments. If inconsistent results are returned then the sort order is undefined
.
如果Function(a, b)
大于 0,则排序b
到小于 的索引a
,即排b
在第一位。
Function(a, b)
当给定一对特定的元素a
并b
作为它的两个参数时,必须始终返回相同的值。如果返回不一致的结果,则排序顺序为undefined
。
回答by Xotic750
See the specification, http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.14
请参阅规范,http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.14
Don't rely on things that w3schools has to say.
不要依赖 w3schools 必须说的话。
If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
如果 comparefn 不是未定义的,则它应该是一个函数,它接受两个参数 x 和 y,如果 x < y,则返回负值,如果 x = y,则返回零,如果 x > y,则返回正值。
回答by aa333
Quoting from ECMA Script Reference:
引用ECMA 脚本参考:
Array.prototype.sort (comparefn)
The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
Array.prototype.sort(比较)
此数组的元素已排序。排序不一定稳定(即比较相等的元素不一定保持其原始顺序)。如果 comparefn 不是未定义的,则它应该是一个函数,它接受两个参数 x 和 y,如果 x < y,则返回负值,如果 x = y,则返回零,如果 x > y,则返回正值。
The rest are implementation details that could differ between interpreters.
其余的是解释器之间可能不同的实现细节。
回答by Yogi Agravat
I am trying to answer your "It does indeed work BUT Why?"
我试图回答你的“它确实有效,但为什么?”
Here is the syntax of the sort method in javascript. Note that the compareFunction is optional.
这是 javascript 中 sort 方法的语法。请注意, compareFunction 是可选的。
array.sort([compareFunction]);
When compareFunction is not provided:
当未提供 compareFunction 时:
When compareFunction is not provided, the default mode of sorting is followed wherein the elements of the array are converted into strings and than compared according to the UTF 16 code unit values and the elements are sorted in ascending order by default.
当未提供 compareFunction 时,将遵循默认的排序模式,其中将数组的元素转换为字符串,然后根据 UTF 16 代码单元值进行比较,默认情况下按升序对元素进行排序。
e.g. For string values, it follows simple UTF 16 code order. like "Banana" appears before "Cat"
例如,对于字符串值,它遵循简单的 UTF 16 代码顺序。就像“香蕉”出现在“猫”之前
for numbers, they first gets converted into strings and then compared according to UTF 16 code oder. So, 80 and 9 gets converted to strings "80" and "9" respectively and "80" comes before "9" according to the UTF 16 order.
对于数字,它们首先被转换为字符串,然后根据 UTF 16 代码顺序进行比较。因此,根据 UTF 16 顺序,80 和 9 分别转换为字符串“80”和“9”,并且“80”在“9”之前。
When compareFunction is provided:
当提供 compareFunction 时:
When compareFunction is provided, then the function takes over the sorting process and all the non-undefined elements gets sorted based on the return value of compareFunction according to the following logic.
当提供 compareFunction 时,该函数将接管排序过程,并根据 compareFunction 的返回值根据以下逻辑对所有未定义的元素进行排序。
If the compareFunction(a,b) returns negative value, a comes first by getting lower index than b.
如果 compareFunction(a,b) 返回负值,则首先获得比 b 低的索引。
If compareFunction(1,b) returns zero then both get the same index and hence do not change place respect to each other but both gets sorted with all other elements.
如果 compareFunction(1,b) 返回零,则两者都获得相同的索引,因此不会改变彼此的位置,但都与所有其他元素一起排序。
If compareFunction(a,b) returns positive value, a gets higher index than b and hence a comes after b.
如果 compareFunction(a,b) 返回正值,则 a 获得比 b 更高的索引,因此 a 在 b 之后。
The example you provided, uses a trick to decide each numbers comparative weightage in terms of its numeric value by subtracting each pair of numbers from the array.
您提供的示例使用一种技巧,通过从数组中减去每对数字来确定每个数字的相对权重。