为什么我认为JavaScript中的数字游戏不起作用?

时间:2017-04-09 14:26:42

标签: javascript

每当我输入一个数字时,即使数字大于另一个数字,它也表示数字太低了。当我输入零或根本不输入任何内容时,它表示您的数字太低。我不明白我已经多次查看我的代码,但我仍然没有发现任何问题。

这是我的代码:

var answer = prompt("Guess a number between 1 and 100");
var number = confirm(Math.round(Math.random()*100));

if (number === answer) {
    confirm("You win!");
} else if(number < answer){
    confirm("Your number was too low!");
} else if (number > answer) {
    confirm("Your number was too high!");
}   

4 个答案:

答案 0 :(得分:2)

首先尝试使用answer函数将parseInt()转换为整数值;

var answer = parseInt(prompt("..."));

答案 1 :(得分:1)

confirm函数返回一个布尔值(truefalse),因此下面一行中的number变量实际上包含一个布尔值。

var number = confirm(Math.round(Math.random()*100));

这搞砸了你的逻辑。

只需将其更改为:

var number = Math.round(Math.random()*100);
confirm(number);

另一个通知

prompt("Guess a number between 1 and 100");返回一个字符串,因此要100%清除,您应该将值转换为数字:

var answer = Number(prompt("Guess a number between 1 and 100"));

答案 2 :(得分:1)

&#13;
&#13;
var answer = prompt("Guess a number between 1 and 100");
var ai_nswer = Math.round(Math.random() * 100);
var number = confirm(ai_nswer);

if (ai_nswer == answer) {
    confirm("You win!");
} else if(ai_nswer > answer){
    confirm("Your number was too low!");
} else if (ai_nswer < answer) {
    confirm("Your number was too high!");
}  
&#13;
&#13;
&#13;

除了你使用的confirm方法不正确之外,逻辑也存在问题。您的if /条件对于高/低是错误的。您应该将随机答案的值存储在临时值中,然后确认它,因为confirm返回一个布尔值,而不是输入值。

答案 3 :(得分:1)

变量answernumber不是同一种类型,因为转换使用var answer中的parseInt,请参阅我的回答:

var answer = prompt("Guess a number between 1 and 100");
var number = confirm(Math.round(Math.random()*100));
answer=parseInt(answer);
if (number === answer) {
    confirm("You win!");
} else if(number < answer){
    confirm("Your number was too low!");
} else if (number > answer) {
    confirm("Your number was too high!");
}