The example in this article analyzes the use of sort () in JavaScript. Share to everyone for your reference. The specific analysis is as follows:
Syntax for functions:
Arrayobject.sort (SortBy)
You are not the right way but your love it
Here also uses the Split function, the purpose is to go to a string of arrays, more commonly used. The array's sort function is then sorted by the values in the arrays, the new array is obtained, and the sorted string is obtained by iterating through the contents of the array.
In the example, by default, it is sorted according to the ASCII code.
If it is a number, what will happen? Give it a try ~
The values in the Modify P are as follows:
20 38 19 32 654 2 123 454 4
The results of the operation are: 123 19 2 20 32 38 4 454 654
It is sorted by character encoding, not the size of the numeric value.
If you want to sort numbers, you need to write a few more lines of code:
The modified code is as follows:
Originarr = Originarr.sort (function (a,b) {return
a-b;
});
Run Result: 2 4 19 20 32 38 123 454 654
The above sort is sorted in a positive order, if it is in reverse order, then you need to change it again:
The return a-b in the function can be changed to b-a.
If the alphabet is sorted, the changed code is as follows:
Originarr = Originarr.sort (function (a,b) {
if (a > B) return-1;
if (a < b) return 1;
return 0;
});
I hope this article will help you with your JavaScript programming.