In JS Array (array) of the sort (sort) Note description _javascript Tips

Source: Internet
Author: User

Just look at the code, and the test results are posted.

Copy Code code as follows:

var Arrdemo = new Array ();

Arrdemo[0] = 10;
ARRDEMO[1] = 50;
Arrdemo[2] = 51;
ARRDEMO[3] = 100;

Arrdemo.sort (); When the sort method is called, the array itself is changed, which affects the original array

alert (Arrdemo);//10,100,50,51 By default the sort method is sorted in ASCII alphabetical order, not what we think is sorted by number size

Arrdemo.sort (function (a,b) {return a>b?1:-1});//small to large sort

alert (Arrdemo);//10,50,51,100

Arrdemo.sort (function (a,b) {return a<b?1:-1});//Sort from large to small

alert (Arrdemo);//100,51,50,10


Conclusion:

1. When the array calls the sort method, it affects itself (rather than generating a new array)

The 2.sort () method is sorted by character by default, so when you sort a numeric array, you can't take it for granted that it will be sorted by number size!

3. To change the default sort behavior (that is, sort by character), you can specify the collation function yourself (as shown in this example)

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.