jeudi 23 juillet 2020

Javascript random function with no repeats? [duplicate]

I've spent some time searching for a solution, but nothing that I've found has worked for me. The solution found at How to efficiently randomly select array item without repeats? seems to be what I'm looking for, but I haven't been able to get it to work properly. I have a random function that displays a single array item each time a button is pushed. See the snippet below for the code that I have so far.

function newText() {
  var randomText = Math.floor(Math.random() * (oddtext.length));
    document.getElementById("thingDisplay").innerHTML = oddtext[randomText];
}

var oddtext = [
  '111',
  '222',
  '333',
  '444',
  '555'
]
<div align="center" id='thingDisplay'></div>

<button onclick="newText()">New Text</button>

I want to prevent the function from displaying a repeat item until the entire array has been run through. Once every item in the array has been displayed, it should loop and be able to choose any item from the array again.




Aucun commentaire:

Enregistrer un commentaire