【问题标题】:math.random() not working when array declared in javascript在 javascript 中声明数组时,math.random() 不起作用
【发布时间】:2017-11-29 06:05:15
【问题描述】:

我试图创建一个函数来为按钮的单击事件选择随机数。但是当我声明一个数组和/或使用array.length乘以Math.random时,似乎函数不起作用(尽管没有显示错误)。在不声明数组或使用其长度的情况下,函数似乎工作正常。这是代码:

const quoteArea = document.querySelector(".quote");
const randomButton = document.getElementById("btn__random");
const quoteArr = [a , b, c];
randomButton.addEventListener("click", randomizeQuote);

function randomizeQuote() {
  const randomNum = Math.floor(quoteArr.length * Math.random());

  quoteArea.innerHTML = randomNum;
}

【问题讨论】:

  • abc 未定义。所以const quoteArr = [a , b, c] 无效。
  • 尝试使用代码 sn-p 按钮创建一个Minimal, Complete, and Verifiable example。我打赌你会更快得到准确的答案! (假设您只是缩短了您的 quoteArr 声明,而真正的问题是其他问题)
  • @JKillian 这是我的第一个问题。仍在弄清楚一切是如何运作的
  • @SpencerWieczorek 谢谢。发现了问题。

标签: javascript arrays random


【解决方案1】:

const quoteArea = document.querySelector(".quote");
const randomButton = document.getElementById("btn__random");
const quoteArr = ['a' , 'b', 'c'];
randomButton.addEventListener("click", randomizeQuote);

function randomizeQuote() {
  const randomNum = Math.floor(quoteArr.length * Math.random());

  quoteArea.innerHTML = randomNum;
}
<button id='btn__random'>Random</button>
<p class='quote'></p>

您没有正确定义 quoteArr 数组,其中 a、b、c 未定义,已更改为 quoteArr = ['a' , 'b', 'c'];

【讨论】:

    猜你喜欢
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2017-05-04
    • 2018-08-11
    • 2015-08-13
    • 2015-05-29
    相关资源
    最近更新 更多