【问题标题】:How can i choose one random item from an array?如何从数组中选择一个随机项?
【发布时间】:2014-12-04 14:46:48
【问题描述】:

我尝试了以下代码,但还是不行:

<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;

程序是 rand 值打印 0 到 1000,就像 newx0 值一样

【问题讨论】:

  • 你能整理一下你的代码(比如关闭标签等,这样它就完整了)并解释一下它有什么不好的地方吗?
  • text 已经是一个数组,但是您将该数组推入另一个数组newx0 - 这是故意的吗?
  • newx0.push(text); 这就是原因。
  • 问题是 rand 值打印 0 到 1000 就像 newx0 值一样。

标签: javascript html arrays random


【解决方案1】:

new0 是一个数组,其中包含一个元素:您的另一个 text 数组。这意味着newx0.length 始终是1。你为什么要做那个数组包装器呢?为什么不只是有

var rand = text[Math.floor(Math.random() * text.length)];
           ^^^^                            ^^^^

改为?

【讨论】:

  • 是否有可能:现在我有 0 到 1000...而且我还需要更多的 4 倍时间...所以我必须有一个编号为 0 到 1000 和 5 次的数组...例如 0,....1000, 0, ....,1000 等等?
【解决方案2】:
/**
 * 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?

【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2021-07-06
    • 2011-01-24
    • 2020-10-04
    • 2015-02-18
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多