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

后端 未结 3 1939
小鲜肉
小鲜肉 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;
    }
    

提交回复
热议问题