Array sort and reverse Usage Analysis in Javascript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the use of arrays sort and reverse in Javascript. The example analyzes the precautions and related skills for using sort and reverse, which has good reference value, for more information about how to use the array sort and reverse in Javascript, see the following example. Share it with you for your reference. The specific analysis is as follows:

The sort () method is used to sort the elements of an array.

Reverse () sorts the elements in the array in reverse order.

First, let's try the following code:

The Code is as follows:

Var values = [1, 0, 5, 15, 10];
Values. reverse ();
Console. log (values );

What is the output result:
[10, 15, 5, 0, 1]

Reverse () is simply to reverse the array, so what we want to talk about next is sort ()

The Code is as follows:

Var values = [1, 0, 5, 15, 10];
Values. sort ();
Console. log (values );


The output result of this function is:
[0, 1, 10, 15, 5]

What's going on?

In fact, the sort () function uses toString () transformation, while the String comparison uses ASCII. Therefore, it is better to write a sort () by ourselves if we need to sort the data.

The Code is as follows:

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 replace-1 and 1, you can reverse sort them.

Current output result:
[0, 1, 5, 10, 15]

A simpler way is to use return value2-value1 in compare;

I hope this article will help you design javascript programs.

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.