Home > Web Front-end > JS Tutorial > Sharing methods for generating randomly shuffled arrays using JS

Sharing methods for generating randomly shuffled arrays using JS

小云云
Release: 2018-01-05 15:02:09
Original
2170 people have browsed it

The example in this article describes how JS generates a randomly scrambled array. I share it with you for your reference, hoping to help you better learn how to generate randomly scrambled arrays with JS.

1. A messy sorting method


function fnLuanXu(num) {
    var aLuanXu=[];
    for (var i = 0; i < num; i++) {
      aLuanXu[i] = i;
    }
    for (var i = 0; i < num; i++) {
      var iRand = parseInt(num * Math.random());
      var temp = aLuanXu[i];
      aLuanXu[i] = aLuanXu[iRand];
      aLuanXu[iRand] = temp;
      //console.log(&#39;i=&#39;+i+&#39;;temp=&#39;+temp+&#39;;rand=&#39;+iRand+&#39;;array[&#39;+i+&#39;]=&#39;+aLuanXu[i]+&#39;;array[&#39;+iRand+&#39;]=&#39;+aLuanXu[iRand]+&#39;;array=[&#39;+aLuanXu+&#39;];&#39;);
    }
    return aLuanXu;
}
//测试:
console.log(fnLuanXu(6));
Copy after login

operation result:

Sharing methods for generating randomly shuffled arrays using JS

2. A less messy sorting method, js built-in function.


function fnLuanXu(num) {
    var aLuanXu=[];
    for (var i = 0; i < num; i++) {
      aLuanXu[i] = i;
    }
    aLuanXu.sort(function(){return Math.random()>0.5?-1:1;})
    return aLuanXu;
}
//测试:
console.log(fnLuanXu(7));
Copy after login

Running results:

Sharing methods for generating randomly shuffled arrays using JS

#Have you learned it? Hurry up and try it out.

Related recommendations:

Detailed explanation of the shuffle function of PHP that scrambles arrays

Randomly shuffles arrays and strings PHP function application test

JS immediately disrupts the array implementation code_javascript skills

The above is the detailed content of Sharing methods for generating randomly shuffled arrays using JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template