-1
在我的代码,我有一个行的代码,使不同的NaN这个神秘的结果,总是:为什么是减法的结果等于为NaN
console.log("The dragon now has"+ (4-totalDamage) + "health left!")
现在totalDamage
等于给自己加了一个名为damageThisRound
变量,这是一个从1到5的随机整数(也包括1和5)。现在,我希望这条线来记录一些像:
The dragon now has 1 health left!
,而是,我得到:
The dragon now has NaNhealth left!
为什么结果等于为NaN,而不是像1,2或3的整数(这应该是(4-totalDamage)
唯一可能的结果)?
全码:
var slaying = true
var youHit = Math.floor(Math.random()*2)
var damageThisRound = Math.floor(Math.random*5 + 1)
var totalDamage = 0
while (slaying) {
if (youHit) {
console.log("You hit the dragon!");
totalDamage += damageThisRound;
if (totalDamage >= 4) {
console.log("You defeated the mighty dragon!");
slaying = false;
} else {
console.log("The dragon now has"+ (4-totalDamage) + "health left!")
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("You lose!");
slaying = false;
}
}
请显示完整的代码示例,以便我们可以重现该问题。具体说明'totalDamage'是如何设置的。 – j08691
totalDamage可能是字符串格式。尝试:'4-parseInt(totalDamage)'(并且确保totalDamage并非已经是NaN,与以前的随机数相加) – dievardump
'totalDamage'是'NaN'或不能转换为有效数字。提供一个完整的示例。 –