创建一个具有随机值的数组 [英] Create an array with random values
本文介绍了创建一个具有随机值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建一个包含40个元素的数组,其随机值介于0到39之间? 喜欢
How can I create an array with 40 elements, with random values from 0 to 39 ? Like
[4, 23, 7, 39, 19, 0, 9, 14, ...]
我尝试使用此处的解决方案:
I tried using solutions from here:
http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm
但是我得到的数组很少是随机的.它会生成很多连续数字的块...
but the array I get is very little randomized. It generates a lot of blocks of successive numbers...
推荐答案
这是一种解决方案,可对唯一的数字列表进行混洗(永远不会重复).
Here's a solution that shuffles a list of unique numbers (no repeats, ever).
for (var a=[],i=0;i<40;++i) a[i]=i;
// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a);
如果要允许重复的值(这不是OP想要的值),则在其他位置查找. :)
If you want to allow repeated values (which is not what the OP wanted) then look elsewhere. :)
这篇关于创建一个具有随机值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文