How does Javascript's sort() work?

前端 未结 9 1929
长情又很酷
长情又很酷 2020-11-22 11:06

How does the following code sort this array to be in numerical order?

var array=[25, 8, 7, 41]

array.sort(function(a,b){
  return a - b
})
9条回答
  •  醉话见心
    2020-11-22 11:42

    Is the array sort callback function called many times during the course of the sort?

    Yes

    If so, I'd like to know which two numbers are passed into the function each time

    You could find out your self with:

    array.sort((a,b) => {
      console.log(`comparing ${a},${b}`);
      return a > b ? 1
                   : a === b ? 0 
                             : -1;
    });
    

    EDIT

    This is the output I've got:

    25,8
    25,7
    8,7
    25,41
    

提交回复
热议问题