Javascript 在 while 循环中评估多个条件
Javascript evaluate multiple conditions within while loop
下面的代码应该不断询问用户从数组中随机选择的乐器,直到他们选对为止。它应该计算猜测的次数并评估每个猜测并确定它是否按字母顺序高于或低于随机。
由于某些原因,我的 If
语句似乎无法正常工作。例如,如果我输入一个不在列表中的项目,代码将不会按预期 return 警报 1。即使仪器输入正确,代码 return 也不是预期的最后一个警报。非常感谢任何帮助。
var MyInstrument;
var guess_input_text;
var guess_input;
var finished = false;
var guess_counter = 0;
function My_instrument()
{
var instruments = ['violin', 'drums', 'pipe', 'harp', 'xylophone'];
instruments.sort();
var randomInstrument = Math.floor(Math.random()*instruments.length);
MyInstrument = instruments[randomInstrument];
while (!finished) {
guess_input_text = prompt("I'm thinking of one of these instruments \n"
+ instruments + "\n can you guess which one it is?"
);
var guess_input = instruments.indexOf(guess_input_text);
alert(guess_input);
guess_counter++;
finished = check_guess();
}
}
function check_guess()
{
if (guess_input == -1)
{
alert("you have not entered instrument from the list");
return false;
}
if (guess_input != -1 && guess_input_text > MyInstrument)
{
alert("your instrument is alphabetically higher than mine");
return false;
}
if (guess_input != -1 && guess_input_text < MyInstrument)
{
alert("your instrument is alphabetically lower than mine");
return false;
}
alert("You got it! The instrument was " + target +
".\n\nIt took you " + guess_counter + " guesses to get it!");
return true;
}
My_instrument();
在 check_guess()
的最后一个警报中
target
未定义
替换为MyInstrument
下面的代码应该不断询问用户从数组中随机选择的乐器,直到他们选对为止。它应该计算猜测的次数并评估每个猜测并确定它是否按字母顺序高于或低于随机。
由于某些原因,我的 If
语句似乎无法正常工作。例如,如果我输入一个不在列表中的项目,代码将不会按预期 return 警报 1。即使仪器输入正确,代码 return 也不是预期的最后一个警报。非常感谢任何帮助。
var MyInstrument;
var guess_input_text;
var guess_input;
var finished = false;
var guess_counter = 0;
function My_instrument()
{
var instruments = ['violin', 'drums', 'pipe', 'harp', 'xylophone'];
instruments.sort();
var randomInstrument = Math.floor(Math.random()*instruments.length);
MyInstrument = instruments[randomInstrument];
while (!finished) {
guess_input_text = prompt("I'm thinking of one of these instruments \n"
+ instruments + "\n can you guess which one it is?"
);
var guess_input = instruments.indexOf(guess_input_text);
alert(guess_input);
guess_counter++;
finished = check_guess();
}
}
function check_guess()
{
if (guess_input == -1)
{
alert("you have not entered instrument from the list");
return false;
}
if (guess_input != -1 && guess_input_text > MyInstrument)
{
alert("your instrument is alphabetically higher than mine");
return false;
}
if (guess_input != -1 && guess_input_text < MyInstrument)
{
alert("your instrument is alphabetically lower than mine");
return false;
}
alert("You got it! The instrument was " + target +
".\n\nIt took you " + guess_counter + " guesses to get it!");
return true;
}
My_instrument();
在 check_guess()
target
未定义
替换为MyInstrument