简体   繁体   English

我怎么猜JavaScript中的数字游戏不起作用?

[英]How come my guess the number game in JavaScript isn't working?

Whenever I enter a number it says the number is too low even if the number is way greater than the other number. 每当我输入一个数字时,即使该数字远大于另一个数字,它也表示该数字太低。 When I enter zero or don't enter anything at all it says your number was too low. 当我输入零或什么都不输入时,表明您的数字太低。 I don't get it i have looked over my code a bunch of times, but I still haven't found any problems. 我不明白,我已经看过很多遍代码了,但是我仍然没有发现任何问题。

Here is my code: 这是我的代码:

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!");
}   

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

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

The confirm function returns a boolean ( true or false ), so the number variable in the line below actually hold a boolean value. confirm函数返回一个布尔值( truefalse ),因此下面一行中的number变量实际上包含一个布尔值。

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

And that messed up your logic. 这弄乱了您的逻辑。

Simply change it to: 只需将其更改为:

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

Another notice 另一个通知

prompt("Guess a number between 1 and 100"); returns a string, so to be 100% clear, you should cast the value to number: 返回一个字符串,因此要100%清除,您应该将值转换为数字:

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

 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!"); } 

Apart from confirm method you are using was not proper, the logic was also problematic. 除了confirm您使用的方法不正确之外,逻辑还存在问题。 Your if conditions were wrong for high/low. 您的条件是否适用于高/低。 You should store the value of your random answer in a temp value, and then confirm it, since confirm returns a boolean value, not the input value. 您应该将随机答案的值存储在临时值中,然后进行确认,因为confirm返回布尔值,而不是输入值。

the variables answer and number is not have the same kind, for convert use parseInt in the var answer , see my answer: 变量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!"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM