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

How can i choose one random item from an array?

本文关键字:一个 随机 项目 数组 选择      更新时间:2023-09-26

我尝试了以下代码,但它不起作用:

<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是从这里获取的:在 JavaScript 中生成特定范围内的随机整数?