This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
                                
                                    (6个答案)
                                
                        
                                2年前关闭。
            
                    
var check = true;
var number = Math.floor(Math.random() * 20);

while (check === true){
var guess = prompt("I picked a number 0 to 20, try to guess it!");
if (number === guess) {
    print("You guessed correctly! Good job!");
    check = false;
}
else if (number < guess) {
    print("\n\You guessed too high!");
}
else if (number > guess) {
    print("\n\You guessed too low!");
}
else {
    print("\n\Error. You did not type a valid number");
    exit();
}
    print("\n\Guess: " + guess + ".");
}


当我尝试运行该程序时,我会一直得到正确的答案,但是它不起作用!即使随机生成的数字是13(我猜是13),它也会通过,并说它是无效的。

最佳答案

您的猜测是一个字符串。这是用户输入的文本,您需要将其转换为数字才能与您的猜测进行比较,因此请替换

var guess = prompt("I picked a number 0 to 20, try to guess it!");




var guess = Number(prompt("I picked a number 0 to 20, try to guess it!");


如果格式不正确,这会将您对用户的猜测转换为数字或特殊值NaN。

您也可以使用==运算符,该运算符将在类型之间自动转换。如果您不熟悉javascript,我建议您不要使用运算符,因为它可能会有一些令人困惑和意外的行为。

10-05 21:02
查看更多