为什么减法结果等于NaN

时间:2015-09-27 22:22:17

标签: javascript

在我的代码中,我有一行代码可以使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;
  }
}

1 个答案:

答案 0 :(得分:3)

var damageThisRound = Math.floor(Math.random*5 + 1)替换为var damageThisRound = Math.floor(Math.random()*5 + 1)

您在致电()时忘记了Math.random()

Math.random*5NaN 然后damageThisRoundNaNtotalDamage也是NaN,因为您尝试向其添加{{1}}。