Just look at the code, and the test results are posted.
Copy Code code as follows:
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, which affects the original array
alert (Arrdemo);//10,100,50,51 By default the sort method is sorted in ASCII alphabetical order, not what we think is sorted by number size
Arrdemo.sort (function (a,b) {return a>b?1:-1});//small to large sort
alert (Arrdemo);//10,50,51,100
Arrdemo.sort (function (a,b) {return a<b?1:-1});//Sort from large to small
alert (Arrdemo);//100,51,50,10
Conclusion:
1. When the array calls the sort method, it affects itself (rather than generating a new array)
The 2.sort () method is sorted by character by default, so when you sort a numeric array, you can't take it for granted that it will be sorted by number size!
3. To change the default sort behavior (that is, sort by character), you can specify the collation function yourself (as shown in this example)