jeudi 24 décembre 2015

How do I make javascript display random names without repeats?

I need to be able to click on a button, then have a few different names come out in a random order without any name being repeated. Displaying random names is simple enough, but I cannot avoid repeats. Here's what I have and I don't understand why it doesn't work.

<script>

var players = []
players[0] = "Billy";
players[1] = "Alex";
players[2] = "Kevin";
players[3] = "Fred";

function tournament(amount) {
    var a = 0, i = 0, place = 1;
    randomlyselect:
    while (a<amount) {
        var randomplayer = Math.floor(Math.random()*(players.length));
        if (players[randomplayer] === document.getElementById('player1').innerHTML || document.getElementById('player2').innerHTML || document.getElementById('player3').innerHTML) {
            continue randomlyselect;
            } 
        else {
            document.getElementById('player'+place).innerHTML = players[randomplayer];
            place++;
            a++;
        }
    }

}

</script>

<button onClick="tournament(4)">Tournament Results</button>

<p id="player1"></p>
<p id="player2"></p>
<p id="player3"></p>
<p id="player4"></p>

I know the problem is the if statement, but I don't know how else I would check if a name was already being displayed. If you know what's wrong with my method of checking if something was already picked or a better way of avoiding repeats please let me know.




Aucun commentaire:

Enregistrer un commentaire