Analysis of the Javascript array sort method

Source: Internet
Author: User
Tags array sort javascript array
Javascript The array. Sort () method is used to sort array items. By default, instances are sorted in ascending order. Code As follows:

The following is a reference clip:
VaR ARRA = [6, 2, 4, 3, 5, 1];
ARRA. Sort ();
Document. writeln (ARRA );
// The result is: 1, 2, 3, 4, 5, 6.

Sort () methodYou can accept a method as a parameter. This method has two parameters. Represent the two array items for each sort comparison. This parameter is executed every time two array items are compared during sort () sorting, and two compared array items are passed as parameters to this function. When the return value of the function is 1, the order of two array items is exchanged. Otherwise, the order is not exchanged.

Example:

The following is a reference clip:
VaR ARRA = [6, 2, 4, 3, 5, 1];
/** // * ARRA. Sort ();
Document. writeln (ARRA );
*/
Function DESC (x, y)
...{
If (x> Y)
Return-1;
If (x <Y)
Return 1;
}
Function ASC (x, y)
...{
If (x> Y)
Return 1;
If (x <Y)
Return-1;
}
ARRA. Sort (DESC); // sort by DESC
Document. writeln (ARRA );
Document. writeln ("<br> ");
ARRA. Sort (ASC); // sort by ASC
Document. writeln (ARRA );

// Output result:
6, 5, 4, 3, 2, 1
1, 2, 3, 4, 5, 6

In addition, an unnamed function can be directly put into the call of the sort () method. In the following example, the odd number is placed at the top and the even number is placed at the bottom. The example is as follows:

The following is a reference clip:
VaR ARRA = [6, 2, 4, 3, 5, 1];
ARRA. Sort (function (x, y )...{
If (X % 2 = 0)
Return 11;
If (X % 2! = 0)
Return-1;
}
);
Document. writeln (ARRA );

// Output: 1, 5, 3, 4, 6, 2

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.