How does Javascript's sort() work?

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

    Pairs of values are compared, one pair at a time. The pairs that are compared are an implementation detail--don't assume they will be the same on every browser. The callback can be anything (so you can sort strings or Roman numerals or anything else where you can come up with a function that returns 1,0,-1).

    One thing to keep in mind with JavaScript's sort is that it is not guaranteed to be stable.

提交回复
热议问题