我正在使用带有某种形式验证的Javascript测验应用程序。我正在尝试这样做,以便如果用户输入的答案不是选项,则代码会告诉用户请输入正确的答案,然后程序将循环回到问题的开头。通过现在编写代码的方式,即使输入是可选选项,在给出输入后它也会循环回到问题的开头。我假设“ do while循环”格式不正确,或者与循环条件有关的原因导致了无限循环。我很难弄清楚这个问题,因此将不胜感激。
答案 0 :(得分:2)
您需要修正比较(不希望问题选择为“ a”或“ b”):
let score = 0;
let question1 = "";
do{
question1 = prompt("In Empire Strikes Back, which one of luke's hand is cut off by Darth Vader? (a) Left (b) Right");
switch(question1.toLowerCase()){
case "a":
alert("Sorry that's incorrect");
break;
case "b":
alert("That's correct!");
score+=1;
break;
default:
alert("That answer wasn't an option, please select one of the options listed");
}
}
while(question1 != "a" && question1 != "b");