Javascript 如何从数组中选择一个随机项?
我尝试了以下代码,但没有成功: 程序是rand VALUE打印0到1000,就像newx0 VALUE是一个数组,它包含一个元素:另一个文本数组。这意味着newx0.length始终为1。你为什么要用数组包装器呢?为什么不干脆Javascript 如何从数组中选择一个随机项?,javascript,html,arrays,random,Javascript,Html,Arrays,Random,我尝试了以下代码,但没有成功: 程序是rand VALUE打印0到1000,就像newx0 VALUE是一个数组,它包含一个元素:另一个文本数组。这意味着newx0.length始终为1。你为什么要用数组包装器呢?为什么不干脆 var rand = text[Math.floor(Math.random() * text.length)]; ^^^^ ^^^^ 相反 /** * Returns a random i
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是从这里获取的:
你能整理一下你的代码吗?比如关闭标签等,这样代码就完整了,并解释一下什么不起作用?文本已经是一个数组了,但是你把这个数组推到另一个数组中newx0-这是故意的吗?newx0.pushtext;这就是为什么。问题是rand VALUE打印的是0到1000,就像newx0 VALUE一样。有没有可能:现在我有0到1000…而且我还需要更多的4x时间…所以我需要一个数字为0到1000的数组和5倍的数组…例如0,…1000,0,…1000等等?
/**
* 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