Home > Article > Web Front-end > Notes on sorting arrays (Array) in js_javascript skills
Just look at the code, the test results are also posted inside
arrDemo[0] = 10;
arrDemo[1] = 50;
arrDemo[2] = 51;
arrDemo[3] = 100;
arrDemo.sort(); //After calling the sort method, the array itself will be changed, which affects the original array
alert(arrDemo);//10,100,50,51 By default, the sort method sorts by ascii alphabetical order, not by numerical order as we think
arrDemo.sort(function(a,b){return a>b?1:-1});//Sort from small to large
alert(arrDemo);//10,50,51,100
arrDemo.sort(function(a,b){return a
alert(arrDemo);//100,51,50,10
1. After the array calls the sort method, it will affect itself (rather than generating a new array)
2. The sort() method sorts by characters by default, so when sorting a numeric array, don’t take it for granted that it will be sorted by numerical size!
3. To change the default sort behavior (that is, sort by characters), you can specify the sorting rule function (as shown in this example)