简体   繁体   中英

hello, I would like to have a different random number, but I always get the same, an idea?

I want to have a random number different when I "click" on my button #roll, but I always get the same number. someone could help me please?

this is my code:

 //création nombre aléatoire function getRandomInt(min, max) { return Math.floor(Math.random() * (max, min + 1)+ min); } numberRandom = getRandomInt(1, 7) //création du lancé de dé const roll = document.getElementById("roll") roll.addEventListener('click',()=>{ alert(numberRandom) })
 <button class="favorite styled" type="button" id="roll"> Lancer le dé </button>

Your problem is that numberRandom = getRandomInt(1, 7) is run once when the page is loaded. If you want a different number each button click, just move it inside the event listener

const roll = document.getElementById("roll")
roll.addEventListener('click',()=> {
  numberRandom = getRandomInt(1, 7)  // <=== move it here
  alert(numberRandom)
})

Additionally, the calculation doesn't not appear to be correct, I believe it should be closer to

Math.floor(Math.random() * (max - min + 1)) + min

If you want to generate a random number when you click then you need to put the code that generates a random number in the function that gets called when you click .

Putting it straight in the top level of the script means you generate a random number once as the page loads.

Every time the function gets called you read the same number from the roll variable.

 function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min+1) ) + min; } const roll = document.getElementById("roll") roll.addEventListener('click',()=>{ var numberRandom = getRandomInt(1, 6) console.log('Dice rolled,you got ',numberRandom); })
 <button class="favorite styled" type="button" id="roll"> Role dice </button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM