samedi 13 octobre 2018

JavaScript - Loop through random values without repeating any in each loop [duplicate]

This question already has an answer here:

I have this page with a button the user can click on to generate a random quote.

I want the quotes to be random. So far, I can do this.

The part I need help with is avoid repeating quotes (at least until all of them have been showed once). In one of my tests, with just 5 quotes, I had the same one appear to me four times in a row... Which is bad.

How can I fix this?

This is what I have:

        function randomize() {
            var myrandom = Math.round(Math.random() * 4)
            if (myrandom == 0)
                document.getElementById("randomQuote").innerHTML = "Quote 01"
            else if (myrandom == 1)
                document.getElementById("randomQuote").innerHTML = "Quote 02"
            else if (myrandom == 2)
                document.getElementById("randomQuote").innerHTML = "Quote 03"
            else if (myrandom == 3)
                document.getElementById("randomQuote").innerHTML = "Quote 04"
            else if (myrandom == 4)
                document.getElementById("randomQuote").innerHTML = "Quote 05"
        }
    <p><button onclick="randomize()" type="button">Random Quote</button></p>
    <p id="randomQuote"></p>



Aucun commentaire:

Enregistrer un commentaire