Analysis of Javascript array sort and reverse

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.