Js of Array of sort considerations

  • 2020-03-30 01:25:29
  • OfStack

Look directly at the code, the test results are also posted in it

var arrDemo = new Array();
 arrDemo[0] = 10;
 arrDemo[1] = 50;
 arrDemo[2] = 51;
 arrDemo[3] = 100;
 arrDemo.sort(); //When the sort method is called, the array itself is changed, affecting the original array
 alert(arrDemo);//10,100,50,51 by default the sort method is sorted alphabetically in ASCII rather than numerically as we think
 arrDemo.sort(function(a,b){return a>b?1:-1});//Sort from small to large
 arrDemo.sort(function(a,b){return a<b?1:-1});//Sort from large to small


1. When the array calls the sort method, it will affect itself (instead of generating a new array)

The 2. Sort () method is sorted by character by default, so when sorting logarithmic arrays, you can't take it for granted that you sort by number!

3. To change the default sort behavior (that is, sort by character), you can specify the sort function (as shown in this example)

Related articles: