如何从数组中选择一个随机项目?
问题描述:
我尝试下面的代码,但仍然没有奏效:
如何从数组中选择一个随机项目?
<html>
<body>
<p id="demo"></p>
<p id="demo2"></p>
<script>
var max=1000;
var text=new Array();
var i=0;
for (i; i<=max ; i++) {
text[i]=i;
}
var newx0=new Array();
newx0.push(text);
var rand = newx0[Math.floor(Math.random() * newx0.length)];
var randomx0=newx0[Math.floor(Math.random()* newx0.length)];
document.getElementById("demo").innerHTML = rand;
document.getElementById("demo2").innerHTML = newx0;
的proglem是兰特有价值打印0到1000就像newx0宝贵
答
new0
是一个数组,其中包含一个元素:您的其他text
阵列。这意味着newx0.length
总是1
。为什么你要做这个数组包装呢?为什么不只是有
var rand = text[Math.floor(Math.random() * text.length)];
^^^^ ^^^^
取而代之?
答
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var array = [wherever your array comes from]; //Set up your array to be sampled
var randIndex = getRandomInt(0, array.length()); //Randomly select an index within the array's range
var randSelectedObj = array[randIndex]; //Access the element in the array at the selected index
getRandomInt从这里拍摄: Generating random whole numbers in JavaScript in a specific range?
你可以整理你的代码(即关闭标签等所以它的完成),并解释什么并不了解它的工作? – 2014-12-04 14:48:42
什么不起作用? – renatoargh 2014-12-04 14:49:32
'text'已经是一个数组了,但是你将该数组推入另一个数组'newx0' - 这是故意的吗? – Jamiec 2014-12-04 14:49:58