How does Javascript's sort() work?

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

    var array=[25, 8, 7, 41]
    
    array.sort(function(a,b){
      console.log(`a = ${a} , b = ${b}`);
      return a - b
    });
    

    OUTPUT

    • a = 8 , b = 25
    • a = 7 , b = 8
    • a = 41 , b = 7
    • a = 41 , b = 8
    • a = 41 , b = 25

    in my Browser (Google Chrome Version 70.0.3538.77 (Official Build) (64-bit) ) in the first iteration, the argument a is the Second element in an array and argument b is the First element of an array.

    if the Compare function returns

    1. Negative Value than b is moved forward to a.
    2. positive Value than a is moved forward to b.
    3. 0(Zero) both a & b will remain as it is.

提交回复
热议问题