创建一个具有随机值的数组 [英] 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屋!
查看全文