Search code examples
javascriptrandomnumbers

How to check if a random generated number is repeated from a button click? JavaScript


This is my code so far. It's basically a randomizer based on images. I got the random pictures to change, but I realized that the images repeat if the generated number is repeated again from the button clicked. Is there a way I can display that message? Like the number has been repeated again. Sorry, I'm still a javascript newbie.

btnRandom.addEventListener('click', function () {
    const numRandom = Math.trunc(Math.random() * 9);
    console.log(numRandom);

    characterEl.src = `img/genshin_characters/card-${numRandom}.webp`;

    if (numRandom) {
        console.log('you got the same character again!');
    }
});

Solution

  • I assume you don't want to random same number twice in a row. So use a variable to remember the last one.

    var last
    btnRandom.addEventListener('click', function() {
      var numRandom
      while ((numRandom = Math.trunc(Math.random() * 9)) === last) {
        console.log("will randomize again");
      }
      console.log(numRandom)
      // characterEl.src = `img/genshin_characters/card-${numRandom}.webp`;
      last = numRandom
    });
    <button id="btnRandom">btnRandom</button>