重复switch语句,直到它有一个有效的答案

时间:2017-07-26 11:57:52

标签: javascript for-loop switch-statement

我是初学者,试图用JavaScript制作文字冒险游戏,我需要重复一个switch语句,直到用户输入有效答案:

*.sink.ganglia.class org.apache.spark.metrics.sink.GangliaSink
*.sink.ganglia.name Name
*.sink.ganglia.host $MASTERIP
*.sink.ganglia.port $PORT

*.sink.ganglia.mode unicast
*.sink.ganglia.period 10
*.sink.ganglia.unit seconds

任何答案都会非常有用 - 谢谢!

2 个答案:

答案 0 :(得分:6)

用一些函数包装代码,并在默认语句

中使用callback函数



function run(){
opts = prompt("Do you want to TALK or LOOK?").toUpperCase();

switch(opts) {
  case "TALK":
    mes = "Is anyone in charge here?";
    speech = "Our leader is in the big building.";
    console.log('talk')
    //talkNot();
    break;
  case "LOOK":
    window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
    break;
  default:
    window.alert("That's not an option.");
    run() //callback 
}
}

run()




答案 1 :(得分:2)

您可以使用简单的do ... while结构。



let next = false
do {
  let opt = prompt("Do you want to TALK or LOOK?").toUpperCase();
  next = false
  switch (opt) {
    case 'TALK':
    case 'LOOK':
      break;
    default:
      next = true
  }
} while (next)