简体   繁体   中英

How can I repeat a switch statement and keep the previous text?

I'm trying to make a random number generator of sorts with 7 different number ranges to choose from. I'm trying to make it so that the statement will repeat itself, with the previous numbers staying in place. Here's my code so far:

`

var roll;
var Dice = prompt("The options are the d4, d6, d8, d10, d12, d20, and d100.");

  switch (true) {
    case (Dice == 4):
      var roll = Math.floor(Math.random() * 4) + 1;
      document.write(roll);
      break;
    case (Dice == 6):
      var roll = Math.floor(Math.random() * 6) + 1;
      document.write(roll);
      break;
    case (Dice == 8):
      var roll = Math.floor(Math.random() * 8) + 1;
      document.write(roll);
      break;
    case (Dice == 10):
      var roll = Math.floor(Math.random() * 10) + 1;
      document.write(roll);
      break;
    case (Dice == 12):
      var roll = Math.floor(Math.random() * 12) + 1;
      document.write(roll);
      break;
    case (Dice == 20):
      var roll = Math.floor(Math.random() * 20) + 1;
      document.write(roll);
      break;
    case (Dice == 100):
      var roll = Math.floor(Math.random() * 100) + 1;
      document.write(roll);
      break;
  
  default:
    alert("Just put the number of sides the die has. Example: to roll a d4, input '4'.")
    location.reload();
    break;
  }

` Any help would be greatly appreciated. I'm a novice to Javascript, so if there's some simple solution to this I overlooked, my apologies.

I tried putting it all in a while statement, with an unchanging variable being the requirement. (I believe my exact code was var repeat = 3; while(repeat = 3) {)

var roll,Dice;

while(true){
    Dice = prompt("The options are the d4, d6, d8, d10, d12, d20, and d100.")
    if (["4", "6", "8", "10", "12", "20", "100"].includes(Dice)) break;
    else alert("Just put the number of sides the die has. Example: to roll a d4, input '4'.")
}
while(true){
    roll = Math.floor(Math.random() * Dice) + 1;
    prompt(roll+ " , press enter to reroll")
}

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