Javascript 添加数组的和但得到NAN
我正在尝试创建一个工作时钟,它允许我输入每天学习的小时数,并得到总小时数。我是否使用了Javascript 添加数组的和但得到NAN,javascript,Javascript,我正在尝试创建一个工作时钟,它允许我输入每天学习的小时数,并得到总小时数。我是否使用了parseInt错误 <html> <head> <title>Time clock</title> <meta charset="utf-8"> </head> <body> <h1 id="header">Time clock<
parseInt
错误
<html>
<head>
<title>Time clock</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="header">Time clock</h1>
<p id="greeting"></p>
<input type="text" id="inp"/>
<button onclick="sumit()">Click</button>
<p id="hours"></p>
<script>
greeting.innerHTML = 'How many hours have you studied?'
function sumit(){
let text = parseInt(document.getElementById("inp").value);
let hours = (document.getElementById("hours"));
let total = 0
for (i = 0; i < 10; i++){
total += parseInt(text[i]);
hours.innerHTML = `You have studied a total of ${text + total} hours.`
}
console.log(total)
console.log(text)
}
</script>
</body>
</html>
时钟
时钟
点击
greeting.innerHTML=“您学习了多少小时?”
函数sumit(){
让text=parseInt(document.getElementById(“inp”).value);
让hours=(document.getElementById(“hours”);
设总数=0
对于(i=0;i<10;i++){
总计+=parseInt(文本[i]);
hours.innerHTML=`您总共学习了${text+total}小时`
}
console.log(总计)
console.log(文本)
}
已定义文本
变量,并为其赋值parseInt
。因此,您的total+=parseInt(text[i])
正在尝试索引一个不可能的数字类型(例如total+=123[0]
)。相反,您可以只执行total+=text
,也可以在声明text
时删除parseInt
调用,然后执行total+=parseInt(text)
,只需进行最小的更改,这应该可以工作:
函数sumit(){
让text=parseInt(document.getElementById(“inp”).value)| 0;
让hours=document.getElementById(“hours”);
设total=0;
总数+=文本;
hours.innerHTML=`您总共学习了${total}小时。`;
}
解释
可以返回parseInt
,因此我们使用NaN
- 你不需要循环任何东西来求和
- 即使您在循环任何内容,也不会像您尝试使用
text[i]
- 即使您在循环任何内容,也不会像您尝试使用
- 您不需要多次将
添加到total
中text
let total=[]
而不是let total=0
我将其更改为0,但仍然得到NaN