Introduction to the use of the sort () method for arrays in JavaScript _javascript tips

Source: Internet
Author: User
Copy Code code as follows:

<title> Array's sort () method </title>

<script>
/*
Sort ()
1, does not produce a copy, direct reference to the original array
2. If you call the method without using parameters, the elements in the array are sorted alphabetically.
To be more precise, sorting is done in the order of character encoding.
To do this, you should first convert the elements of the array into strings (if necessary) for comparison.

3, if you want to sort by other standards, you need to provide a comparison function, the function to compare two values,
It then returns a number that describes the relative order of the two values.
The comparison function should have two parameters A and B, and the return value is as follows:
If a is less than B, a value less than 0 is returned in the sorted array before a should appear in B.
If a equals B, it returns 0.
If a is greater than B, a value greater than 0 is returned.

*/

var arr = [2,4,8,1,22,3];
var arrsort= arr.sort ();//not sorted correctly, the array is converted to a string and then sorted
document.write ("The default sort array is:" + arrsort);//1,2,22,3,4,8
document.write ("<br/>");

comparison function
function Mysort (a,b) {
return a-b;
}

var arrSort2 = Arr.sort (mysort);//Incoming comparison function
document.write ("The array of incoming comparison parameters is:" + arrSort2);
document.write ("<br/>");

document.write ("Original array is:" + arr);

</script>


<body>
<div id= "Time" ></div>
</body>

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.