JavaScript function sort

Source: Internet
Author: User

The sort function is used to sort the elements of an array

Syntax: Arrayobject.sort (sortby);

The parameter sortby is optional and specifies the sort order, which must be a function.

If the method is called without parameters, it is sorted in the order of the subtitles, that is, in the order in which the letters are encoded. To do this, convert the elements of the array into strings 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 that describes the relative positions of these two numbers:

The comparison function should have two parameters A and B, and its return value: If A is less than B, a value that is less than 0 is returned if a is smaller than the number in the sorted digit before B, and A=b returns 0;A>B, which returns a value greater than 0.

function () {

<script type= "Text/javascript" >    function Compare (A, a) {return a-B        ; }var arr=[1,2,3,4,5,21,15];d ocument.write (arr+ ' <br/> ') document.write (Arr.sort (Compare));</script>

  

JavaScript function sort

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.