+ 13

Can you help me fine tune my noob JS function that generates random strings from an array?

https://code.sololearn.com/WzmyGYtrQScA/?ref=app Hi! I have a basic random quote generator. If you click the button, you'll see that the quotes often repeat, because each button click selects a random string. I'd like for it to work such that no quotes repeat, and when all have been selected, a message appears saying something. Do any of you programmers have any suggestions to share with me? đŸ€—đŸ’â€â™‚ïž

14th Jan 2018, 8:11 PM
JMQ
JMQ - avatar
4 Answers
+ 13
Thanks again @visph. I appreciate all of the responses! This is a huge help.
15th Jan 2018, 7:52 AM
JMQ
JMQ - avatar
+ 11
Hm..Something like this? function newQuote(){ var randomNumber = Math.floor(Math.random() * (quotes.length)); if(quotes.length) { document.getElementById('quotes').innerHTML = quotes.splice(randomNumber, 1); } else { document.getElementById('quotes').innerHTML = "No more quotes..."; } }
14th Jan 2018, 11:32 PM
K137(){/**/};
K137(){/**/}; - avatar
+ 7
Here's an external discussion regarding various formulation for random number generation in JavaScript: https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range Hth, cmiiw
14th Jan 2018, 8:48 PM
Ipang
+ 5
I would suggest some improvement to @ĐĐ°Ń‚Đ°Đ»ŃŒŃ ОшурĐșĐŸĐČĐ° solution: rather than just picking and deleting your quotes array items, so you will end with no quote to display when all had already been, keep them in another 'backup' array, to be able to replace the empty original one when leangth reach zero... Also, define a global var to hold the reference to the targeted html element for displaying quote: that's not necessary to perform a call to .getElementById() method each time newQuote() functio is called (button clicked) ^^ function newQuote(){ if (!quotes.length) { quotes = done; done = []; } var randomNumber = Math.floor(Math.random() * (quotes.length)); out.innerHTML = quotes[randomNumber]; done.push(quotes.splice(randomNumber,1)); } var out, done = []; window.onload = function() { // initialization of targeted output element global ref out = document.getElementById('quotes'); }
15th Jan 2018, 5:39 AM
visph
visph - avatar