建立在JavaScript中随机值的数组 [英] create a array with random values in javascript

查看:120
本文介绍了建立在JavaScript中随机值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能创建具有40元素的数组,随机值从0到39?
[4,23,7,39,19,0,9,14 ...]

How can I create a 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:

<一个href=\"http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm\">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. :)

这篇关于建立在JavaScript中随机值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆