循环遍历对象数组并返回随机对象值-JavaScript

时间:2020-06-02 00:09:22

标签: javascript

我试图遍历对象数组并显示数据中的随机引用,到目前为止,我的代码返回 undefined 。知道为什么吗?

到目前为止的代码。

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}

我试图随机显示引号(字符串)。

3 个答案:

答案 0 :(得分:4)

您可能希望获得报价:

const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)].quote;

我不知道您要对循环做什么。

答案 1 :(得分:1)

您可以使用此函数返回随机报价:

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)];
    const quote = document.createElement("DIV");
    quote.textContent=randomQuote.quote;
    const author = document.createElement("DIV");
    author.textContent=randomQuote.author;  document.getElementById("container").appendChild(quote).appendChild(author);
}

randomQuotes();
<div id="container"></div>

答案 2 :(得分:1)

您可以使用rando.js更方便地进行此操作。如果您想使用此代码,请不要忘记将script标签添加到HTML文档的开头。

const quotesToUse = [
  {quote: "This was the biggest quote ever - Array Object", author: "Derek Bullshido"},
  {quote: "Hey hows it going - Array Object", author: "Paul Frank"},
  {quote: "Why can I say that - Array Object", author: "Derek Paul"},
];

var randomValueFromArray = rando(quotesToUse).value;
console.log(randomValueFromArray.quote);
<script src="https://randojs.com/1.0.0.js"></script>