The sort () method is used to sort the elements of an array.
Reverse () to reverse the elements in an array
First, let's try the following code:
| The code is as follows |
Copy Code |
var values = [1, 0, 5, 15, 10]; Values.reverse (); Console.log (values); |
What would the output be:
[10, 15, 5, 0, 1]
Reverse () is simply to turn the array upside down, so the next thing you want to spit out is sort ()
| The code is as follows |
Copy Code |
var values = [1, 0, 5, 15, 10]; Values.sort (); Console.log (values); |
The output of this function turns out to be:
[0, 1, 10, 15, 5]
What's going on?
In fact, the sort () function uses the ToString () transformation, and string comparisons are ASCII, so it's better if we need to sort, or write ourselves a sort ().
| The code is as follows |
Copy Code |
var values = [1, 0, 5, 15, 10]; function Compare (value1, value2) { if (value1 < value2) { return-1; else if (value1 > value2) { return 1; } else { return 0; } } Values.sort (Compare); Console.log (values); |
If you change it-1 and 1, you can sort it backwards.
Now the output results:
[0, 1, 5, 10, 15]
A simpler formulation is to use return value2-value1 within compare ();