我正在尝试学习JavaScript,当我开始MDN教程时,我尝试单独进行第一个练习,到目前为止效果还不错。但是确实有一种奇怪的情况。
游戏会生成一个1到100之间的随机数,并且用户有10个猜测来找出该数字。
为此我将游戏简化为1-10。
当随机数是9而我猜是10时,代码显示我的输入值太低。我不明白为什么会这样。在任何其他情况下,它的工作都完全符合预期。
出于调试原因,第一次猜测后,对话框中会显示随机数。
这是我的代码:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = (Math.random() * 10).toFixed(0);
guess = prompt("Guess a number from 1 to 10");
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
先谢谢了。如果您想在代码中看到某些内容想要发表评论,我希望能收到反馈并变得更好,即使它与该内容没有直接关系;)
答案 0 :(得分:4)
问题是,您正在使用字符串,如果将两个字符串与<
进行比较,它将只比较所需的字符,直到找到较小的字符为止(较小的是整数表示) )比另一个:
console.log("10" < "9");
此处只会将"1"
与"9"
进行比较,这意味着将字符代码49与字符代码57相比较。
49小于57,表示整个表达式为true
。您可以了解有关ASCII字符代码here的更多信息。
您应该改用Numbers:
console.log(Number("10") < Number("9"));
您仅在处理字符串,因为prompt()
和Number.toFixed()
都返回字符串。如果将这些内容封装在Number()
调用中,则您的游戏有效:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = Number((Math.random() * 10).toFixed(0));
guess = Number(prompt("Guess a number from 1 to 10"));
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
答案 1 :(得分:1)
Javascript提示返回一个字符串。实际上,输入文本框始终返回字符串。因此,当您输入10时,它将返回“ 10”,并且toFixed()也将返回字符串。
因此您需要从代码中更正两行
number = parseInt((Math.random() * 10).toFixed(0));
guess = prompt("Guess a number from 1 to 10");
guess = parseInt(guess);
此外,您还需要检查NAN状况是否更安全。