What do return -1, 1, and 0 mean in this Javascript code?

后端 未结 3 1934
小鲜肉
小鲜肉 2021-02-01 10:29

Here is the context:

function compare (value1, value2) {
    if(value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
          


        
相关标签:
3条回答
  • 2021-02-01 10:50

    The sort method takes an optional comparison function that determines the resulting sort order based on the following:

    • if its return value is less than zero, then sort value1 to a lower index than value2
    • if its return value is zero, then leave the indices of value1 and value2 unchanged with respect to each other
    • if its return value is greater than zero, then sort value1 to a higher index than value2

    Note that given these rules, it's possible to shorten your comparison function to the following:

    function compare(value1, value2) {
        return value1 - value2;
    }
    
    0 讨论(0)
  • 2021-02-01 11:06

    -1 means that value1 is less than value2

    0 means that value1 is equal to value2

    1 means that value1 is greater than value2

    0 讨论(0)
  • 2021-02-01 11:08

    No, -1, 0, and 1 in a comparison function are used to tell the caller how the first value should be sorted in relation to the second one. -1 means the first goes before the second, 1 means it goes after, and 0 means they're equivalent.

    The sort function uses the comparisons in the function you pass it to sort the function. For instance, if you wanted to sort in reverse order, you could make line 3 return 1; and line 5 return -1.

    0 讨论(0)
提交回复
热议问题