Array.Sort of JavaScript Learning notes

Source: Internet
Author: User

Arrayname.sort () Method:

The function is to implement sorting (by ASCII encoding or by number size), can be used without parameters or parameters, the default ascending order when no parameter. When you have a parameter that can be sorted in ascending or descending order, the parameter must be a method with a return value, and the method expression will exchange two number of digits if it is greater than 0 o'clock. That

Arrayname.sort (Expression {if (expression >0)   Exchange order; else if (expression <0)    does not perform an operation;    else//Expression =0  Select specific actions according to browser support;});

where the expression (= = method) will determine the sorting principle, specifically the instance is

Arrayname.sort (function(b) {    if(a>b)        return 1;     else if (a<b)         return -1;     Else// (a=b)         return 0;});   

will be sorted in ascending order, the corresponding way to achieve descending order is:

Arrayname.sort (function(b) {    if(a>b)        return -1;     Else if (a<b)         return 1;     Else // a===b        return 0;});

When the array content of the comparison is a number, the above expression can be simplified to:

// Ascending arrayname.sort (function(b) {    return A-b;}); // Descending arrayname.sort (function(A, b    ) {return b-a;});

In addition, the sort method, depending on the expression, also implements the ability to sort based on the content of the element, as described in Array.prototype.sort ().

Array.Sort of JavaScript Learning notes

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.