如何创建一个包含 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:
freewebdesigntutorials/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; // stackoverflow/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. :)