[英]Adding splitted values in loops
我建議您看一下這張圖片,然后看一下我編寫的代碼:
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
for(i = 0; i <= splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
}
我從顯示“輸入數字和/或單詞列表”的框中獲取值,然后將其拆分。 我將其拆分,以便獲得所有像這樣的“ 1 2 3”數字,因此可以添加它們。 我為此使用for循環。 for循環遍歷每個數字,然后將其相加。 但是當我按下按鈕時,它顯示為未定義。
為什么我變得不確定?
您將變得不確定,因為您正在顯示數組的最后一個元素的值,而不是像問題中提到的那樣Sum
。
以下代碼始終將resultNumberTotal
splitted[i]
的值覆蓋resultNumberTotal
的值。 因為, 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;
}
您需要使用+=
運算符或使用類似.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"/>
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)
}
為了獲得最佳實踐,請確保只允許輸入字段輸入數字:)祝您好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.