我建议你看看这张照片,然后你看看我写的代码:
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
for(i = 0; i <= splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
}
我从框中输出值&#34;输入数字和/或单词列表&#34;我正在分裂它。我分开了所以我有这样的所有数字&#34; 1 2 3&#34;所以我可以添加它们。我使用for循环。 for循环遍历每个数字然后添加它。但是当我按下按钮时,它显示我未定义。
为什么我未定义?
答案 0 :(得分:0)
您未定义,因为您正在显示数组的最后一个元素的值,而不是如您在问题中提到的Sum
那样。
以下代码始终以resultNumberTotal
的值覆盖splitted[i]
的值。因为,for
循环为i <= splitted.length
迭代它到达数组中不存在的索引,当你得到一个对象上不存在的属性时,你得到undefined
for(i = 0; i < splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
所以,为了做总和,你需要制作像
这样的代码function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
var total = 0;
for(i = 0; i < splitted.length; i++) {
var numberValue = +splitted[i];
if(!isNaN(numberValue)){
total = total + numberValue ;
}
}
document.getElementById("resultNumberTotal").value = total;
}
答案 1 :(得分:0)
您需要以某种方式添加数字,使用+=
运算符,或使用.reduce()
之类的内容,如下所示。
function addNumbers() {
var val = document.getElementById("listInput").value;
document.getElementById("resultNumberTotal").value = val.split(" ").reduce(function(runningTotal, currentArrayElement) {
// make sure the value they typed is a number
// if not, fail gracefully and simply ignore it
if (!isNaN(Number(currentArrayElement))) {
// if it is a number, add it to the running total
runningTotal+= Number(currentArrayElement);
}
return runningTotal; // return the running total
}, 0); // start with 0 as the initial value for runningTotal
}
<input type="text" id="listInput" placeholder="insert values here..." style="width: 300px;" />
<button onclick="addNumbers()">Add Numbers</button>
<br/>
<br/>
<hr/>
Number Total: <input id="resultNumberTotal"/>
答案 2 :(得分:0)
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
//make sure that the values are in a number format
document.getElementById("resultNumberTotal").value = splitted.reduce(function(a, b) {return Number(a) + Number(b);}, 0)
}
为了获得最佳实践,请确保仅允许输入字段的数字:)祝你好运