var userchoice;
var compchoice = parseFloat(Math.ceil(Math.random()*10));
console.log(compchoice);
function guess () {
if (compchoice === document.getElementById("userguess").value) {
alert("You guessed it!");
location.reload()
}
else if (document.getElementById("userguess").value > compchoice) {
alert("That was a little high, try again")
}
else if (document.getElementById("userguess").value < compchoice) {
alert("That was a little low, try again")
}
else if (isNaN(document.getElementById("userguess").value)) {
alert("Guess a number bro")
}
}
这是我的代码。我是一个初学者,只是在搞概念。现在的问题是,如果您猜对了数字,则 guess()
中的第一个 if
语句应该运行,但它没有。另一个 else if
运行了,所以我很困惑问题是什么。如有任何帮助,我们将不胜感激。
最佳答案
这将返回一个字符串:
document.getElementById("userguess").value
这将返回一个数字:
parseFloat(Math.ceil(Math.random()*10))
由于类型不同,===
将返回false
。一些解决方案:
- 使用
==
进行比较 - 将字符串转换为数字:
+str
- 将数字转换为字符串:
''+num
关于javascript - 如果条件不满足,什么时候应该满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023375/