Because the original sort API is actually the first to compare the number of converted to a string and then compare, so it is not easy to use
So prepare to customize a comparer function:
1 //Sort Principle--->sort (arr,compare)2 functionSort (arr,compare) {3 if(compare===undefined) {//If compare is undefined, a compare original comparator is created, converted to a string for comparison, and if a custom comparer is passed in, the custom comparer is called to sort4Compare=function(A, B) {//Original Comparator5 returnString (a) >string (b)? 1://greater than 0 returns 16String (a) >string (b)?-1://less than 0 returns-170;//otherwise returns 08 }9 }Ten for(varr=1;r<arr.length;r++) {//Number of comparisons One for(vari=0;i<arr.length-r;i++) {//before and after 22 comparison A if(Compare (arr[i],arr[i+1]) >0) {//if x is greater than Y - varTemp=arr[i];//give the value of X to the third-party temp -ARR[I]=ARR[I+1];//give the value of Y to x theArr[i]=temp;//and give the value of temp to X. -}//where x and Y are swapped . - } - } + } - //To create a custom comparer function + /*function cmp (x, y) { A return x-y; at }*/ - varcmp=function(A, B) {returnA-B;}//can be written directly in the sort (CMP), sort (function (A, b) {return-A;}); - vararr=[8,3,123,15,4,9,7,1,2]; -Arr.sort ();//Use the default sort sort -Console.log (Arr.join ("")); - vararr2=[8,3,123,15,4,9,7,1,2]; inArr2.sort (CMP);//sorting using a custom comparer function, if sort (CMP ()), is performed only once, and sort (CMP) means that the CMP function is given sort -Arr2.reverse ();//In descending order, sort ascending, then invert with reverse toConsole.log (Arr2.join (""));
javascript--Array--sort Comparator