The sort () method in JavaScript

Source: Internet
Author: User

Now in learning JavaScript, finding the sort () function is a bit of a strange thing (maybe it's my level problem-_-! , so just record what you found here. Sort () The parameter of this method is very strange, it must be a function, but also an optional parameter, if there are no parameters, it will default in the dictionary order of strings (even if the value is converted to a string to handle). This parameter is to be able to compare the size of two values, such as:

function Sortnumber (A, b) {
return a-B; The return is their difference, if the value is less than 0, will be a row in front, if greater than 0, will be b in front, if it is 0, just casually. (Bubble Sort Method!!) )
}

The application is as follows (this example is too classic!!) ):

<script type= "Text/javascript" >
function Sortnumber (A, A,) {return a-B}
var arr = new Array (3)
Arr[0] = "10";
ARR[1] = "5";
ARR[2] = "4";
document.write (arr + "<br/>");
document.write ( arr.sort(sortNumber) );
</script>

Then the arrangement of the original 10,5,4 will become 4,5,10. Here is a description of the process, obviously sortnumber should have two parameters, but we call when a parameter is not, how to compare ah? Here is the case when Arr calls sort from the first number, 10 is no number compared to it, so the second, that is 5, then 10 will be compared with 5, so it will call Sortnumber and 10 and 5 in, this is the character of sort ().

The sort () method in JavaScript

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.