Javascript array random sorting instance analysis and javascript instance analysis

Source: Internet
Author: User

Javascript array random sorting instance analysis and javascript instance analysis

This article describes how to implement random sorting of javascript arrays. Share it with you for your reference. The details are as follows:

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

Var arr = [9, 3, 1, 2, 5, 8, 4, 7, 6, 0]; arr. sort (); document. write ("array elements after normal sorting:" + arr. join (",") + "<BR/> ");

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.

Function randomSort (a, B) {return Math. random ()-0.5;} arr. sort (randomSort); document. write ("array elements after random sorting:" + arr. join (",") + "<BR/> ");

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

I hope this article will help you design javascript programs.

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.