Skip to content Skip to sidebar Skip to footer

Using The Same Random Number In Multiple Places (javascript)

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 easi

Solution 1:

Try calling randomIndexinside your click handler.

button.addEventListener("click", function(){
  var random = randomIndex();
  quoteBox.textContent = '"' + quotes[random] + people[random] + '"';
});

That will assign a new index each time the click handler runs, but will use the same index to access both quotes and people.

Solution 2:

Instead of having 2 arrays for quotes and people, use a unique array of objects, each one having 2 members quote and people.

var quotes = [
    {quote: 'The quote text', author: 'Its author'},
    {quote: 'A second quote text', author: 'The 2nd author'},
    // ...
];

button.addEventListener("click", function(){
  var quote = quotes[randomIndex()];
  quoteBox.textContent = '"' + quote.quote + quote.index + '"';
});

Solution 3:

Try this :)

var randomIndex = function() {
  returnMath.floor(Math.random() * quotes.length);
};

button.addEventListener("click", function(){
  var index = randomIndex();
  quoteBox.textContent = '"' + quotes[index] + people[index] + '"';
});

Solution 4:

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.

var quotes = [{
  quote: 'something something darkside',
  person: 'family guy sith lord'
}, {
  quote: 'something something evil',
  person: 'family guy sith lord'
}, {
  quote: 'blah blah blah',
  person: 'foobar'
}];

var
  quoteEl = document.querySelector('#quote'),
  personEl = document.querySelector('#person'),
  button = document.querySelector('#button');

button.addEventListener("click", getQuote);

getQuote();

functiongetQuote() {
  var quote = quotes[randomIndex(quotes.length)];
  quoteEl.innerHTML = quote.quote;
  personEl.innerHTML = quote.person;
}

functionrandomIndex(max) {
  returnMath.floor(Math.random() * max);
};
blockquote {
  padding: .5em;
  margin: 1em;
  background: #eee;
  border-left: 1em solid #aaa;
  color: rgba(37, 37, 37, .87);
}
#person {
  text-decoration: none;
  color: rgba(37, 37, 37, .87);
}
#person::before {
  content: ' -- ';
}
#person:hover {
  text-decoration: underline;
}
<blockquote><pid="quote"></p><footer><ahref="#"id="person"></a></footer></blockquote><buttonid="button">get a random quote
</button>

Post a Comment for "Using The Same Random Number In Multiple Places (javascript)"