Sort Array ()

Source: Internet
Author: User
Tags array sort

Sort Array ()

The sort () method causes the elements in the array to be arranged in a certain order.

Grammar:

Arrayobject.sort (method function)

Parameter description:

1. If the < method function is not specified, it is sorted in Unicode code order.

2. If you specify the < method function, then sort by the < method function > The sorting method specified.

Myarray.sort (SortMethod);

Note: The function compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B with the following return values:

A return value of <=-1 indicates that A appears before B in the sorted sequence.   If the return value >-1 && <1, then A and B have the same sort order. A return value of >=1 indicates that A appears after B in the sorted sequence.

1. Use sort () to sort the array with the following code:

<script type= "Text/javascript" >  var myarr1 = new Array ("Hello", "John", "Love", "JavaScript");   var myarr2 = new Array ("n", "+", "Max", "6", "+", "1");  document.write (Myarr1.sort () + "<br>");  document.write (Myarr2.sort ());</script>

Operation Result:

hello,javascript,john,love1,100,16,50,6,80

Note: The above code does not sort the numbers by the size of the numeric values.

2. To achieve this, you must use a sort function with the following code:

<script type= "Text/javascript" >  function Sortnum (A, a) {  return a-B;//ascending, such as descending, put "A-a" into "b-a"} var Myarr = new Array ("n", "+", "a", "6", "+", "1");  document.write (Myarr + "<br>");  document.write (Myarr.sort (sortnum));</script>

Operation Result:

80,16,50,6,100,11,6,16,50,80,100

Sorting array sort ()

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.