About the Javascript sort () function

Source: Internet
Author: User

I encountered a problem today.

VaR arr = [3, 1, 16, 34, 7, 8];

Arr. Sort ();

The returned result is [,]. It is different from what I want to achieve.

I have read the interface description.

Arrayobject. Sort (sortby ).

Sortby must be a function.

If no parameter is used when this method is called, the elements in the array are sorted alphabetically. More precise, the elements are sorted by character encoding. To achieve this, first convert the elements of the array into strings (if necessary) for comparison.

If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number indicating the relative sequence of the two values. The comparison function should have two parameters, A and B. The returned values are as follows:

If a is less than B, A should appear before B in the sorted array, then a value smaller than 0 is returned.

If a is equal to B, 0 is returned.

If a is greater than B, a value greater than 0 is returned.

After reading it, use a function to try it out.

Ascending

Function ascend (a, B ){

Return A-B;

}

Descending Order

Function DESC (a, B ){

Return B-;

}

After testing, there is no problem in ascending order of arr. Sort (ascend) and descending order of arr. Sort (DESC.

Related Article

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.