The cause of the problem:
In the post of an inside question, many people use the sort () method to sort the array. Seemingly reasonable code, the result of the operation is frequently wrong. Why is it? Because a lot of people miss out a little bit, that is sort () sorted by default in ASCII alphabetical order, rather than according to our assumed number size.
The problem arises:
For example, we use the sort () array [ -12,3,6,5,100] to sort in ascending order, so what is the result? [ -12,100,3,5,6]. The array [ -12,10,3,6,5] is sorted in ascending order? The answer is [ -12,10,3,5,6]. Sort the array [ -12,70,3,5,6]? [ -12,3,5,6,70] The result is equal to the size of the data.
Workaround:
Although sort () does not sort by number, it has always been a ploy, and we can specify the collation function by changing the default sort behavior (arranged by character):
For example: Arr.sort (A, B) {return-A-A;});( From small to Large) arr.sort (function (A, b) {return b-a;}); (from large to small)
There are also collation functions such as Arr.sort (A, b) {return a>b?1:-1}) (from small to Large) arr.sort (function (A, b) {return a>b?1:-1}) (from large to small)
The specific code is as follows:
1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title></title>6<script type= "Text/javascript" >7 8 vararr =NewArray ("abbbbbbb", "BCCCC", "Dhacker", "Efff", "FJJJ", "", "ghhh", "Hoo");9 Arr.sort ();Ten for(vari = 0; i < arr.length; i++) { One Document.writeln (Arr[i]); A } - - varNumarr =NewArray (12,23,100,4,23,34,2,-15); the //Numarr.sort (function compare (A, b) {return-A-B;}); -Numarr.sort (function(A, B) {returnA>b?-1:1}) - - for(vari = 0; i<numarr.length; i++) { +document.write (Numarr[i] + "<br>"); - } + A alert (Numarr); at -</script>> - - -<body> - in</body> -
Sort the pits in the sorting