为什么array.sort(function(a, b){return a-b})是从小到大排序

根据mozilla的官方说明文档

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

简而言之,如果比较函数 function(a, b)结果是小于0的,那么第一个参数a就一定是在第二个参数b的前面。如果结果是大于0的,那么第二个参数b就在第一个参数a的前面。

因此,如果是 function(a, b){return a-b} 那么当a<b时,(a-b) < 0。a就排在b前面,当a>b时, 把b排在a前面,所以总是从小到大排序。

同理,如果是function(a, b){return b-a} 当a<b时,(b-a) > 0,b在a之前,当a>b时,(b-a) < 0,a在b的前面,总之是从大到小排序。

至于a=b的情况,正如上述文档所说,并没有官方统一标准,所以不同浏览器可能采取不同的方法。

ps: 一个小小的疑惑:虽然mozilla的官方文档对array.sort()的解释很清楚了,但是ECMA-262里却并没有提到function(a, b)结果>0时应该如何处理。

  • There must be some mathematical permutation π of the nonnegative integers less than len, such that for every nonnegative integer j less than len, if property old[j] existed, then new[π(j)] is exactly the same value as old[j],. But if property old[j] did not exist, then new[π(j)] does not exist.
  • Then for all nonnegative integers j and k, each less than len, if SortCompare(j,k) < 0 (see SortCompare below), then π(j) < π(k). (from page 141 to page 142 of The Fifth Edition of ECMA-242 )

Comments