This article mainly describes the precautions for sorting arrays (sort) in js. If you need it, you can refer to it for help.
Check the Code directly. The test result is also pasted with the Code as follows: var arrDemo = new Array (); arrDemo [0] = 10; arrDemo [1] = 50; arrDemo [2] = 51; arrDemo [3] = 100; arrDemo. sort (); // After the sort method is called, the array itself will be changed, that is, the original array alert (arrDemo) will be affected; // 10,100, 50, 51 by default, the sort method is sorted in ascii alphabetical order, rather than the arrDemo which we think is sorted by number size. sort (function (a, B) {return a> B? 1:-1}); // sort alert (arrDemo) in ascending order; // 51,100, arrDemo. sort (function (a, B) {return a <B? 1:-1}); // sort alert (arrDemo) from large to small; //, 50, 10 Conclusion: 1. after the sort method is called for the array, it will affect itself (instead of generating a new array) 2. by default, the sort () method is sorted by characters. Therefore, when sorting a numeric array, you cannot take it for granted that it will be sorted by number size! 3. To change the default sort behavior (sort by characters), you can specify the sort rule function (as shown in this example)