我是编码新手,已经使用do while和prompt设置了一个任务。我已经创建了下面的代码。如果我放格兰芬多以外的东西,上面写着"那不是你的房子,再试一次!"所以当我再次尝试时,它没有重复,而是返回到最初的提示,询问他们将住在哪所房子里。有人能帮我纠正吗?非常感谢。
var house;
do {house = prompt("With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
if (prompt == 'Hufflepuff' || 'Ravenclaw' || 'Gryffindor');
house = prompt('That is not the house for you, try again');
} while (house != 'Gryffindor');
house = alert ("Yes that is the house for you!")
我希望它不断重复"那不是你的房子,再试一次",直到用户键入格兰芬多,而不是回到";你将被安置在哪栋房子里?请进入格兰芬多、拉文克劳、赫夫勒帕夫或斯莱特林">
对于某些人来说,这将是一个简单的解决方案,我仍在自己通过教程等进行修复,但我是编码新手,所以你能提供的任何帮助都将是很棒的。
感谢
if (prompt == 'Hufflepuff' || 'Ravenclaw' || 'Gryffindor')
如果你想将变量与不同的值进行比较,你需要像一样重复比较
if (prompt == 'Hufflepuff' || prompt == 'Ravenclaw' || prompt == 'Gryffindor')
或者,您可以使用类似的switch语句
switch (prompt) {
case 'Hufflepuff':
case 'Ravenclaw':
case 'Gryffindor':
// prompt is either Hufflepuff | Ravenclaw | Gryffindor
break;
default:
// else
break;
}
如果给出正确答案,则可以使用无限循环while(true)
和break
。break
将退出最近的循环。
do {
const house = prompt("With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
if(house == 'Gryffindor')
{
break;
}
alert('That is not the house for you, try again');
} while (true);
alert("Yes that is the house for you!")
然而,这缺乏其他答案之一的清晰度。把它留在这里,因为这是从代码到工作的自然过程,但如果你想要更好的代码,请选择另一个答案!
一个更简单的方法是不使用do ... while
循环。无论如何,使用它都有点令人困惑的控制流,所以这要容易得多:只需使用while
循环本身!
let house = prompt( "With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
// Just repeat the question until your value is equal to Gryffindor
while( house !== "Gryffindor" ) house = prompt( "That is not the house for you, try again" );
alert( "Yes that is the house for you!" )
如果您坚持使用do ... while
循环(注意:不推荐),解决方案是不使用If条件——您的while
本质上就是这样。只要while
条件中的代码评估为true,它就会执行另一轮do
:
let house = prompt( "With which house will you be placed? Please enter Gryffindor, Ravenclaw, Hufflepuff, or Slytherine!");
// It's best _not_ to go to your do..while at all if your condition is met
// The issue, obviously, is that you have to repeat the condition twice!
// That's clearly against the "Don't Repeat Yourself" principle.
if( house !== "Gryffindor" ) do {
house = prompt( "That is not the house for you, try again" );
} while( house !== "Gryffindor" )
alert( "Yes that is the house for you!" )
为什么不推荐?因为do ... while
循环非常令人困惑,所以condition
只在大量代码之后列出,这与大多数情况下(如if
或switch
)的情况相反。我从未在任何地方的生产中见过do ... while
代码,最好保持这种状态。