【问题标题】:Getting NaN when attempting to increment score尝试增加分数时获得 NaN
【发布时间】:2020-02-10 12:03:24
【问题描述】:

我目前正在尝试对以下代码进行故障排除:

function getStuff(){
  document.querySelector('#tuna').onclick=scorefunc;    
}

function scorefunc() {
  var scorep;
  scorep = scorep + 1;
  document.getElementById("scorez").innerHTML = "You have found me: " + scorep + " times";
}

基本上,当用户单击 id 为 tuna 的段落元素 (p) 时, scorefunc 运行。每次单击时,我都尝试将分数加 1,但它却显示“您已找到我 NaN 次”

如果这是错误的,我的 HTML 代码如下所示:

<p id ="scorez">You have found me: </p>

提前致谢:)

【问题讨论】:

  • scorep 开始于undefined。你不能给undefined加1,它会给你NaN
  • 哇,我太傻了!欣赏它,伙计!通过设置 var scorep = 0; 修复
  • 另外,如果函数内部将 scorep 定义为 0,则每次调用该函数时都会将其重置为 0。所以将你的 scorep 初始化移到函数之外:)
  • 正在研究那个 Syndey 哈哈!谢谢你。对本地/全局感到困惑,因为我习惯了 python 并且您的建议修复了它
  • Python 使用完全相同的作用域:ideone.com/xZvqTZ

标签: javascript html


【解决方案1】:

问题是scorepundefined。您声明它(即var scorep),但您从未定义它,因此您实际上是在尝试将undefined1 添加在一起,这当然会产生NaN

将您的声明更改为var scorep = 0 以解决问题。

此外,如果您希望 scorep 在每次单击 p 元素时增加 1,您将不得不创建 closure 或在本地范围之外声明变量。

var scorep = 0
function scorefunc() {
  scorep += 1
  document.getElementById("scorez").innerHTML = `You have found me: ${scorep} times`
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2020-02-10
    • 2023-03-24
    • 2019-09-13
    • 2021-08-24
    • 2014-05-29
    相关资源
    最近更新 更多