Random sorting of javascript Arrays

Source: Internet
Author: User
We will test the random sorting of 0-9, Mr into data viewsourceprint? 1 vararr [,]; viewsourceprint? 1arr. sort (); 2document. write (& quot; array element after normal sorting: & quot; + arr. join (& quot;, & quot;) + & quo

We will test the random sorting of 0-9, Mr into data

View sourceprint? 1 var arr = [,];

 


View sourceprint? 1 arr. sort ();

2 document. write ("array elements after normal sorting:" + arr. join (",") +"
");


Array elements after normal sorting: 0, 1, 2, 3, 4, 5, 6, 8, 9

Define a random function that returns positive or negative numbers at random. The sort function determines whether the two values are in positive or reverse order based on the positive or negative values returned by random.


View sourceprint? 1 function randomSort (a, B ){

2 return Math. random ()-0.5;

3}

4

5 arr. sort (randomSort );

6 document. write ("array elements after random sorting:" + arr. join (",") +"
");


Array elements after random sorting: 3, 1, 7, 4, 8, 6, 2, 0, 9, 5

Array elements after random sorting: 8, 3, 5, 0, 7, 6, 4, 2


Author: "blog smaller"
 

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.