javascript - 从嵌套在进一步嵌套在数组中的对象中的数组中随机选择元素的逻辑

标签 javascript arrays object dom

我正在尝试为报价应用程序创建逻辑。有一个包含对象作为元素的数组,该对象还有两个键,引号和作者。现在我希望当点击一个按钮(新报价)时,它会从 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/

相关文章:

javascript - 队列列表输出没有像应有的那样输出

javascript - 从值javascript中获取键

c# - 管理 C# WPF 应用程序客户端 PC 文件夹中的 3000 个文件

代码不会检查一维数组中多个重复的整数

C编程: Replacing if statements

c# - 使用接口(interface)将数据传递到数据层是否可以接受

JavaScript 日期排序

javascript - 在javascript中将rgba颜色值转换为0xFFFFFFFF形式

c# - 当客户端脚本显示时正确调整 ModalPopupExtender 的大小

javascript - 获取未匹配到单个数组的数组元素的结果