I'm creating a random quote generator that is supposed to give you a random quote along with the person who said it, but I've created two separate arrays because it'll make it easier to edit the visual aspects of the page later on. The first array has the quote itself and the second array has the names of the people who said them. I would like to generate one random number and then use that as my index on both arrays, thus getting a random quote and the corresponding person who said it.
The first thing I tried was this:
var randomIndex = function() {
return Math.floor(Math.random() * quotes.length);
};
button.addEventListener("click", function(){
quoteBox.textContent = '"' + quotes[randomIndex()] + people[randomIndex()] + '"';
});
But that gives me two different random numbers (because I'm calling the function twice, I suppose). I then tried setting the random number to a variable and using that as the index, but that doesn't change unless I refresh the page and I want it to change on the click of a button. Is what I want to do possible?
I would suggest instead of maintaining two arrays use one that stores objects with key value pairs of what you need to use in the quote. see below.
Instead of having 2 arrays for quotes and people, use a unique array of objects, each one having 2 members
quote
andpeople
.Try calling
randomIndex
inside your click handler.That will assign a new index each time the click handler runs, but will use the same index to access both
quotes
andpeople
.Try this :)