JavaScript implements an array of random order

Source: Internet
Author: User

Usually the most we use is to put an irregular array in order from large to small or small to large, but sometimes we may encounter an ordered array of chaos to achieve the effect of random sorting, this is what I want to introduce to you today;

First I looked for some on Baidu, found a more common method

1 function Randarray (arr) {2     return arr.sort (function() {3         return math.random ()-0.5; 4     }); 5 }

However, there are some problems with this approach, even errors, reference links: https://www.h5jun.com/post/array-shuffle.html

And here are two more practical ways to introduce to you:

Method One:

function Randarray (a) {    var b = [];      while (A.length > 0) {//iterate over an element in a array each time, and then delete the element until the length of the A array is        0;var index = parseint (Math.random () * ( A.length-1));        B.push (A[index]);         1);    }     return b;}

Method Two:

function Randarray (a) {    var len = a.length;      for (var i = 0; i < len-1; i++) {        var index = parseint (Math.random () * (Len- i)); c12/>var temp = A[index];         = a[len-i-1];         -I-1] = temp;    }     return A;}

JavaScript implements an array of random order

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.