Introduction to the sort () method of arrays in javascript

Source: Internet
Author: User

Introduction to the sort () method of arrays in javascript

The sort () method of the array is used for sorting. This article describes how to use the sort () method in javascript.

The Code is as follows:

<Html>

<Head>

<Title> sort () method of the array </title>

 

<Script>

/*

Sort ()

1. No copies are generated and the original array is directly referenced.

2. If no parameters are used when this method is called, the elements in the array are sorted alphabetically,

To be more precise, sort by character encoding.

To achieve this, first convert the elements of the array into strings (if necessary) for comparison.

 

3. If you want to sort by other criteria, you need to provide a comparison function. This function must compare two values,

Return 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.

 

*/

 

Var arr = [2, 4, 8, 1, 2, 3];

Var arrSort = arr. sort (); // The array is not sorted correctly. The array is converted to a string and then sorted.

Document. write ("the default sorting array is:" + arrSort ); //,

Document. write ("<br/> ");

 

// Comparison Function

Function mysort (a, B ){

Return a-B;

}

 

Var arrSort2 = arr. sort (mysort); // pass in the comparison Function

Document. write ("the input comparison parameter array is:" + arrSort2); // sort the parameters correctly.

Document. write ("<br/> ");

 

Document. write ("the original array is:" + arr );

 

</Script>

 

</Head>

 

<Body>

<Div id = "time"> </div>

</Body>

 

</Html>

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.