为什么我的表单输出 NaN?

Why is my form outputting NaN?

所以我有这个执行非常基本计算的表格,当我提交它时,结果为 NaN。

让我感到困惑的是,当我对分配给每个输入值的变量之一进行 typeof 时,它 returns "number",但我得到的结果是 NaN .谁能告诉我为什么或我做错了什么?

这是我的 HTML:

<form name="baddiesCost">
     <input type="number" placeholder="Total Caught" name="goomba" id="goomba-form">
     <input type="number" placeholder="Total Caught" name="bobombs" id="bob-ombs-form">
     <input type="number" placeholder="Total Caught" name="cheepCheeps" id="cheep-form">
     <button id="submitForm">Submit</button>
</form>
 <h1 id="total"></h1>

这是我的 JavaScript:

document.baddiesCost.addEventListener("submit", function(e) {
  e.preventDefault();
  var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
  var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
  var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
  var goombaCost = 5;
  var bobombsCost = 7;
  var cheepCost = 11;
  var showTotal = document.getElementById("total");
  var total = goombaCaught + bobombsCaught + cheepsCaught;
  showTotal.textContent = cheepsCaught;
  console.log(bobombsCaught);
  console.log(typeof bobombsCaught);
})

此语句 document.baddiesCost.bobombs.value * bobombsCost; 使用了此时未定义的变量 bobombsCost

因此,它类似于:document.baddiesCost.bobombs.value * undefined; 将是 NaN

要解决此问题,请在使用前初始化变量,如下面的代码所示:

document.baddiesCost.addEventListener("submit", function(e) {
      e.preventDefault();

      var goombaCost = 5;
      var bobombsCost = 7;
      var cheepCost = 11;

      var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
      var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
      var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;

      var showTotal = document.getElementById("total");
      var total = goombaCaught + bobombsCaught + cheepsCaught;
      showTotal.textContent = cheepsCaught;
      console.log(bobombsCaught);
      console.log(typeof bobombsCaught);
    })

总之,NaN是数字类型,可以参考下面的post了解更多的解释。