Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从数组中选择一个随机项?_Javascript_Html_Arrays_Random - Fatal编程技术网

Javascript 如何从数组中选择一个随机项?

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

我尝试了以下代码,但没有成功:

程序是rand VALUE打印0到1000,就像newx0 VALUE是一个数组,它包含一个元素:另一个文本数组。这意味着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是从这里获取的:

你能整理一下你的代码吗?比如关闭标签等,这样代码就完整了,并解释一下什么不起作用?文本已经是一个数组了,但是你把这个数组推到另一个数组中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