Home > Web Front-end > JS Tutorial > How to generate a randomly scrambled array in JS

How to generate a randomly scrambled array in JS

亚连
Release: 2018-06-15 17:57:41
Original
2403 people have browsed it

This article mainly introduces the method of JS to generate randomly scrambled arrays, involving related operation skills of random sorting of javascript arrays. Friends who need it can refer to it

The example of this article tells the story of JS generating randomly scrambled arrays Methods. Share it with everyone for your reference, the details are as follows:

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

Running results:

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

Run results:

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed interpretation of plotly.js drawing library usage tutorial (detailed tutorial)

How to create and upload photos in AngularJS Instructions (detailed tutorial)

How to dynamically add an instance of Li element in javaScript

How to dynamically add an instance of Li element with style in jquery HTML tag element

How to dynamically add li tags and add attributes and bind event methods in jQuery

The above is the detailed content of How to generate a randomly scrambled array in 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