简体   繁体   English

JavaScript - 从数组 1 中选取随机元素,我想从数组 2 中获取相同的元素编号

[英]JavaScript - picking random element from array 1, I want to get the same element number from array 2

Let's say I have array 1 and array 2, both having 5 elements.假设我有数组 1 和数组 2,它们都有 5 个元素。

I wrote a simple function to get a random element from array 1:我编写了一个简单的函数来从数组 1 中获取一个随机元素:

function getQuote() {
    var returnQuote = Math.floor(Math.random() * quotes.length);
    document.getElementById('quoteBox').innerHTML = quotes[returnQuote];
}

This function returns random element from the array "quotes".此函数从数组“quotes”中返回随机元素。 But I have another array, called "authors".但我有另一个数组,称为“作者”。 The elements there are ordered in the corresponding order like array 1 - quote 0 is coming from author 0 and so on.那里的元素按相应的顺序排序,如数组 1 - 引用 0 来自作者 0 等等。

Is it possible that if let's say arr.如果让我们说 arr. 1 element 2 is chosen, the same element 2 from arr. 1 元素 2 被选中,与来自 arr 的元素 2 相同。 2 to be picked as well? 2也要被选中?

So I can print out the quote on position 2 and also pull the corresponding author from arr 2. on position 2 so I can print it in the corresponding box of my "web app".所以我可以打印出位置 2 上的引用,并从位置 2 上的 arr 2. 中拉出相应的作者,以便我可以将其打印在我的“网络应用程序”的相应框中。

I hope my question makes sense.我希望我的问题是有道理的。

And I also hope it is not a dumb one.我也希望它不是一个愚蠢的。 I am just starting to learn/practice JavaScript.我刚刚开始学习/练习 JavaScript。

Cheers!干杯!

Yes it's possible.是的,这是可能的。 The returnQuote is just referencing a number, and so you can use that number as the index for whatever arrays you wish. returnQuote只是引用一个数字,因此您可以使用该数字作为您希望的任何数组的索引。

Note that if you wanted to add more data to the same element, if you try to use the = assignment operator, it'll overwrite the previously inserted data.请注意,如果您想向同一元素添加更多数据,如果您尝试使用=赋值运算符,它将覆盖先前插入的数据。

I'd either concatenate the values from the two arrays, or use .insertAdjacentHTML for any subsequent calls.我要么连接两个数组中的值,要么使用.insertAdjacentHTML进行任何后续调用。

function getQuote() {
  var returnQuote = Math.floor(Math.random() * quotes.length);
  document.getElementById('quoteBox').innerHTML = quotes[returnQuote] + quotes2[returnQuote];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM