简体   繁体   English

为什么返回-1在javascript中排序第二个数组之前的第二个值

[英]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. 我喜欢去想它的方式是,如果你减去两个数字ab ,你会得到一定意味着负数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.

相关问题 为什么第二个收益率首先在此生成器中返回 - Why does the second yield return first in this generator 为什么我的 for 循环只将第一个结果返回到 JavaScript 中的数组? - Why does my for loop only return the first result to an array in JavaScript? 为什么我的 Javascript 循环只返回第一个值? - Why does my Javascript loop only return the first value? 为什么第二个循环在第一个循环之前执行? - Why does the second loop execute before the first loop? javascript 用第二个数组值替换第一个数组值。 第一个数组长度为 2,第二个数组长度为 7 - javascript replace first array value with second array value. First array length is 2 and second one length is 7 如何通过第一个数组的输入返回第二个数组的值 - How to return the value of the second array through the input of the first array Javascript 排序功能。 按第一个然后按第二个排序 - Javascript sort function. Sort by First then by Second 为什么JavaScript结果总是返回第一个值? - Why the JavaScript result always return first value? 无法将第二个数组对象值添加到 javascript 中的第一个对象数组中 - Unable to add second array object value into first array of objects in javascript javascript-按第二个数组的顺序排序 - javascript - sort by the order of a second array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM