[英]why does return -1 sort the first value of an array before the second in javascript
function compare (value1, value2) {
if(value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
var values = [0, 6, 8, 5];
values.sort(compare);
alert(values); // 0,5,6,8
I know that -1 means the first goes before the second and 1 means it goes after but what is the logic behind this? 我知道-1表示第一个在第二个之前,1个意味着它在追求但这背后的逻辑是什么? does this -1 0 and 1 apply to methods other than sort?
这个-1 0和1是否适用于排序以外的方法?
The way I like to think about it is if you subtract two numbers a
from b
and you get a negative number that must mean that b
was larger, if you get a positive number then a
was larger, and if you get 0
then they were both equal. 我喜欢去想它的方式是,如果你减去两个数字
a
从b
,你会得到一定意味着负数b
较大,如果你得到一个正数,然后a
是更大的,如果你得到0
,然后他们两者都是平等 sort()
will sort based on which is smaller, larger, and equal. sort()
将根据哪个更小,更大和相等来排序。
Ex: 例如:
case of -1 -1的情况
a = 6 and b = 7
a - b = -1 // b is larger
case of 1 案例1
a = 6 and b = 5
a - b = 1 // a is larger
case of 0 0的情况
a = 6 and b = 6
a - b = 0 // both are equal
function compare (value1, value2) { return value1 - value2; } var values = [0, 6, 8, 5]; values.sort(compare); console.log(values); // 0,5,6,8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.