+ 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? đ€đââïž
4 Answers
+ 13
Thanks again @visph. I appreciate all of the responses! This is a huge help.
+ 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...";
}
}
+ 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
+ 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');
}