Home > Article > Web Front-end > Sharing methods for generating randomly shuffled arrays using JS
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('i='+i+';temp='+temp+';rand='+iRand+';array['+i+']='+aLuanXu[i]+';array['+iRand+']='+aLuanXu[iRand]+';array=['+aLuanXu+'];'); } return aLuanXu; } //测试: console.log(fnLuanXu(6));
operation result:
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:
#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!