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

Sharing methods for generating randomly shuffled arrays using JS

小云云
小云云Original
2018-01-05 15:02:092146browse

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));

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));

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!

Statement:
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