我尝试了以下代码,但它没有工作:
<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是rand有价值的打印0到1000,就像newx0有价值的
答案 0 :(得分:4)
new0
是一个数组,其中包含一个元素:您的另一个text
数组。这意味着newx0.length
始终为1
。你为什么要做那个数组包装呢?为什么不拥有
var rand = text[Math.floor(Math.random() * text.length)];
^^^^ ^^^^
代替?
答案 1 :(得分:0)
/**
* 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?