我一直在做一个小游戏,你要求人们拼写一个1-10的随机数。
我使用if/else
语句完成了此操作。我尝试添加一项功能,如果用户输入“退出”字样,游戏会显示一条提示“再见”的提示。而游戏将会破裂。但是当我测试它并输入“退出”字样时,它会显示一条警告,说“再见”,但它不会中断。
我试图找出解决方案,但我无法弄明白。任何有用的提示?
P.S我是编码的新手,请不要判断我缺乏知识。
var numSpelling = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
var num;
var answer;
var i;
alert('If you want to exit the game, just enter the word quit');
for (i = 0; i < 10; i++) {
num = Math.floor(Math.random() * 10) + 1;
answer = prompt('What is the spelling for the number ' + num);
while (true) {
if (answer == 'quit') {
alert('Goodbye');
break;
} else if (answer == numSpelling[num]) {
alert('Correct');
break;
} else {
alert('Incorrect');
answer = prompt('Please try to spell ' + num + ' again')
}
}
}
答案 0 :(得分:2)
答案 1 :(得分:1)
break
只会打破while
循环。但是在它for
循环之后它将再次运行它的下一次迭代。
您可以在for
循环中添加更多条件 - i < 10 && answer !== 'quit'
let numSpelling = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
let num, answer;
alert('If you want to exit the game, just enter the word quit');
for(let i = 0; i < 10 && answer !== 'quit'; i++) {
num = Math.floor(Math.random() * 10) + 1;
answer = prompt('What is the spelling for the number ' + num);
while (true) {
if(answer == 'quit') {
alert('Goodbye');
break;
} else if (answer == numSpelling[num]) {
alert('Correct');
break;
} else {
alert('Incorrect');
answer = prompt('Please try to spell ' + num + ' again')
}
}
}
答案 2 :(得分:1)
您只是在while loop
而不是for loop
let quit = false;
while(true) {
if(answer == 'quit'){
alert('Goodbye');
quit = true;
break;
}else if(answer == numSpelling[num]){
alert('Correct');
break;
} else {
alert('Incorrect');
answer = prompt('Please try to spell ' + num + ' again')
}
}
if (quit) { break; }