下面的代码应该一直询问用户从阵列中随机选择的乐器,直到它们正确。它应该计算猜测的数量加上评估每个猜测,并确定它是按字母顺序高于还是低于随机。
出于某些原因,我的If
陈述似乎无法正常运作。例如,如果我输入一个不在列表中的项目,代码将不会按预期返回警报no.1。即使输入的仪器正确,代码也不会返回任何内容而不是最后一次警报。非常感谢任何帮助。
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();
答案 0 :(得分:0)
在check_guess()
target
未定义
将其替换为MyInstrument