How does Javascript's sort() work?

前端 未结 9 1942
长情又很酷
长情又很酷 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:51

    run this code. You can see the exact step by step sorting process from the beginning to the end.

    var array=[25, 8, 7, 41]
    var count = 1;
    array.sort( (a,b) => { 
    console.log(`${count++}). a: ${a} | b: ${b}`);
    return a-b;
    });
    console.log(array);
    

提交回复
热议问题