javascript - 我收到 NaN 错误

标签 javascript html calculator

我在这个计算器脚本中遇到 NaN 错误: 有什么想法吗?

这是文本格式的整个 html:

https://www.dropbox.com/s/i3u429bn5bjd4i9/orecalculator.txt

<script language="JavaScript">

var IDs = [22,17425,17426,1223,17428,17429,1225,17432,17433,1232,17436,17437,1229,17865,17866,21,17440,17441,1231,17444,17445,1226,17448,17449,20,17452,17453,11396,17869,17870,1227,17867,17868,18,17455,17456,1224,17459,17460,1228,17463,17464,19,17466,17467,1230,17470,17471];

function calculate(i){
    while (i + 1 < IDs.length) {
        var y=document.getElementById('reward');
        var x=document.getElementById(IDs[i]);
        y.value=parseInt(y.value)+parseInt(x.value);
        i++;
    }
}
</script>

最佳答案

我已经在控制台中运行这段代码并找到了以下输出

document.getElementById('reward')
//output <input type=​"text" id=​"reward">​
document.getElementById('reward').value
//""
parseInt(document.getElementById('reward').value)
//NaN
parseInt("")
//NaN

解释

空字符串的 parseInt 是 NaN

解决方案

使用

Reward: <input type="text" id="reward" value="0">

代替

Reward: <input type="text" id="reward">

修复:JS 代码

function calculate(i){
    while (i + 1 < IDs.length) {
        var y=document.getElementById('reward');
        var x=document.getElementById(IDs[i]);
        y.value=parseInt(y.value|0)+parseInt(x.value|0);
        i++;
    }
}

关于javascript - 我收到 NaN 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24516918/

相关文章:

php - 如何使用 Google Analytics 捕获网站 API 流量数据?

Javascript window.open 不执行任何操作

html - 如何在内容较少的情况下将网页右下角的 div 对齐?

javascript - Google 计算器 API 的替代品

c++ - 2个小错误,我无法用C++理解!

java - 计算器不会接受用户输入

javascript - Angular 模板缓存不起作用

javascript - 如何使用 momentjs 查找某个国家/地区的可用时区

javascript - 为什么简写函数与类一起使用会导致 "this"未定义?

html - 水平居中表格行