Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){…})

后端 未结 4 601
醉梦人生
醉梦人生 2021-02-02 03:12

I am trying to understand how exactly sort() works and how I am supposed to use it.

I did some research (google) and went through the similar questions here on stackover

4条回答
  •  鱼传尺愫
    2021-02-02 04:04

    According to Array reference (http://www.w3schools.com/jsref/jsref_sort.asp):

    By default, the sort() method sorts the values as strings in alphabetical and ascending order.

    So your first understanding about sort() is correct. However, the second and third are not yet correct. First of all, they are both the same case, which is providing a sorting function to the sort() method. This method should compare the a and b, and return negative, zero, or positive values, indicating if a is less than, equals, or greater than b. So for example, you can still compare your myArr using the name property like this:

    myArr.sort(function(a,b) {
      return a.name.localeCompare(b.name);
    });
    

提交回复
热议问题