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('i='+i+';temp='+temp+';rand='+iRand+';array['+i+']='+aLuanXu[i]+';array['+iRand+']='+aLuanXu[iRand]+';array=['+aLuanXu+'];'); } return aLuanXu; } //测试: console.log(fnLuanXu(6));
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));
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!