我正在尝试为报价应用程序创建逻辑。有一个包含对象作为元素的数组,该对象还有两个键,引号和作者。现在我希望当点击一个按钮(新报价)时,它会从 quotesArray 中随机选择他的作者的报价。
我在这里面临两个问题,
问题 1: 我无法从嵌套在对象内的引号键中选择随机元素。
问题 2: 它随机选择一个作者,而不是从具有引号数组的同一对象中选择作者。
我希望我是清楚的。
这是我的代码。
HTML代码:
<div class="quote-app">
<div class="quote">Quote</div>
<div class="author">Author</div>
<button class="new-quote">New Quote</button>
</div>
我的 JS 代码:
let quote = document.querySelector(".quote"),
author = document.querySelector(".author"),
newQuote = document.querySelector(".new-quote");
let quotesArray = [
{
author: "Author1",
quotes: ["a", "b", "c", "d", "e"]
},
{
author: "Author2",
quotes: ["f", "g", "h"]
},
{
author: "Author3",
quotes: ["i", "j"]
},
{
author: "Author4",
quotes: ["k", "l", "m", "n"]
}
];
newQuote.addEventListener("click", function(){
quote.innerHTML = quotesArray[Math.floor(Math.random() *
quotesArray.length)].quotes[Math.floor(Math.random() * quotes.length)];
author.innerHTML = quotesArray[Math.floor(Math.random() *
quotesArray.length)].author;
});
当我写 (Math.random() * 3) 而不是 quotes.length 时,它工作正常但我想从 quotes.length 中选择元素而不是特定长度。
如果有人能解决我的问题,我会的。
最佳答案
var selectedQuotes = quotesArray[Math.floor(Math.random() * quotesArray.length)];
quote.innerHTML =
selectedQuotes.quotes[Math.floor(Math.random() * selectedQuotes.quotes.length)];
// Before you could choose an author from a different quote. This fixes that.
author.innerHTML = selectedQuotes.author;
那应该行得通。问题似乎是您没有引号
。我们通过在选择之前存储所选数组来解决这个问题。
关于javascript - 从嵌套在进一步嵌套在数组中的对象中的数组中随机选择元素的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458086/