随机引用机器使用数组

问题描述 投票:-1回答:3

我正在建立我的第一个随机报价机免费代码营项目。我需要我的JavaScript代码才能工作

var quotes = [["Imitation is suicide.", "-Ralph Waldo Emerson"] ["Flatter yourself critically.", "-Willis Goth Regier" ] ["Don’t look for society to give you permission to be yourself.", "-Steve Maraboli"] ["If things go wrong, don’t go with them.", "-Roger Babson"] ["Wanting to be someone else is a waste of who you are.", "-Kurt Cobain"] ["Do what you can, with what you have, where you are.", "-Theodore Roosevelt"] ["If you cannot be a poet, be the poem.", "-David Carradine"] ["Be there for others, but never leave yourself behind.", "-Dodinsky"]];

function newQuote() {
  var randomNumber = math.floor(math.random() * (quotes.length));
  document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
  }
javascript arrays
3个回答
0
投票

你忘记了数组中的逗号

var quotes = [["Imitation is suicide.", "-Ralph Waldo Emerson"], ["Flatter yourself critically.", "-Willis Goth Regier" ], ["Don’t look for society to give you permission to be yourself.", "-Steve Maraboli"], ["If things go wrong, don’t go with them.", "-Roger Babson"], ["Wanting to be someone else is a waste of who you are.", "-Kurt Cobain"], ["Do what you can, with what you have, where you are.", "-Theodore Roosevelt"], ["If you cannot be a poet, be the poem.", "-David Carradine"], ["Be there for others, but never leave yourself behind.", "-Dodinsky"]];

function newQuote() {
  var randomNumber = Math.floor(Math.random() * (quotes.length));
  document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
  }
  
  newQuote();
<div id="quoteDisplay"></div>

0
投票

您的代码有几个问题:

  1. 数组中的元素应以逗号分隔。 所以不应该写[["quote1", "author1"] ["quote2", "author2"]],它应该是[["quote1", "author1"],["quote2", "author2"]]
  2. 在Window对象下没有任何叫做math的东西,它是Math。因此,不应该调用math.floor,而应该调用Math.floor
  3. quotes[randomNumber]为您提供引号字符串和作者的数组。因此,当您写入元素的innerHTML时,它将转换为字符串。您可以通过显式调用quotes[randomNumber].join("")来避免使用逗号,或者可以声明一个不同的元素分隔符,例如新行。

var quotes = [["Imitation is suicide.", "-Ralph Waldo Emerson"], ["Flatter yourself critically.", "-Willis Goth Regier" ], ["Don’t look for society to give you permission to be yourself.", "-Steve Maraboli"], ["If things go wrong, don’t go with them.", "-Roger Babson"], ["Wanting to be someone else is a waste of who you are.", "-Kurt Cobain"], ["Do what you can, with what you have, where you are.", "-Theodore Roosevelt"] ,["If you cannot be a poet, be the poem.", "-David Carradine"], ["Be there for others, but never leave yourself behind.", "-Dodinsky"]];

function newQuote() {
  var randomNumber = Math.floor(Math.random() * (quotes.length));
  document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber].join("<br>");
}

newQuote();
<div id="quoteDisplay">

</div>

0
投票

首先,以错误的格式声明数组在数组中的元素之间插入“,”。

第二,没有数学课而是使用数学课。

© www.soinside.com 2019 - 2024. All rights reserved.