我认为下一步很简单,但是我一直想弄清楚我的头发。我要投入一些钱,然后通过“提交”按钮输入。当我输入多个值时(因为我还要列出花在钱上的东西),我试图获取所有花的钱的总数,但是我要么得到NaN要么什么都没有。从理论上讲,我希望每次点击确认时,文本框中的金额便会添加到当天的总额中。
我一直在尝试将值推入数组中,然后使用for循环对其求和,但也许我正在使它变得比所需复杂。这是我的代码:
function totalSpent() {
var total= 0;
var spent = document.getElementById("moneySpent").value;
var array = [];
// check if the entered value is number
if (isNaN(Number(spent))) {
alert("Numbers only");
} else {
var spent = parseInt(document.getElementById("moneySpent").value);
for (var i=0; i<spent.length;++i){
array.push(parseFloat(spent[i].value));
}
total = array.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
youSpent.innerHTML=`Total Spent Today: ${total}`;
}
}
<input type="amount" size=25 Placeholder="How much did you spend?"
id="moneySpent">
<input type="button" value="confirm" onClick="totalSpent()">
<br>
<h2 id="youSpent"> Total Spent Today:
</h2>
答案 0 :(得分:1)
在这里您是我的朋友,为了使您的代码正常工作,我做了一些最小的更改:
array.push(spent)
一次,无需循环array.reduce
添加一个初始值0
var array = [];
function totalSpent() {
var total= 0;
var spent = document.getElementById("moneySpent").value;
// check if the entered value is number
if (isNaN(Number(spent))) {
alert("Numbers only");
} else {
var spent = parseInt(document.getElementById("moneySpent").value);
array.push(spent);
total = array.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
}, 0);
youSpent.innerHTML=`Total Spent Today: ${total}`;
}
}
<input type="amount" size=25 Placeholder="How much did you spend?"
id="moneySpent">
<input type="button" value="confirm" onClick="totalSpent()">
<br>
<h2 id="youSpent"> Total Spent Today:
</h2>
答案 1 :(得分:0)
您必须在函数之外声明数组,否则,每次调用该函数时,您都会擦除旧值
https://jsfiddle.net/c3L5q6pa/
var array = [];
function totalSpent() {
var spent = parseFloat(document.getElementById("moneySpent").value);
// check if the entered value is number
if (isNaN(spent)) {
return alert("Numbers only");
}
array.push(spent)
const total = array.reduce((previous, current) => previous + current);
youSpent.innerHTML=`Total Spent Today: ${total}`;
})
答案 2 :(得分:0)
所以,我看到了两件事,第一件事:
var spent = parseInt(document.getElementById("moneySpent").value);
当您将字符串输入值转换为“ parseInt”时,您失去了String.length属性,因此您的for()无法使用。
第二,如果您要对所有数字求和,我不认为需要将所有值推入一个数组然后循环并求和,您可以执行以下操作:
} else {
total = 0;
var spent = document.getElementById("moneySpent").value;
for (var i=0; i<spent.length;++i) total += parseInt(spent[i]);
youSpent.innerHTML=`Total Spent Today: ${total}`;
}
答案 3 :(得分:0)
/etc/rc.d
<input type="amount" size=25 Placeholder="How much did you spend?" id="moneySpent">
<input type="button" value="confirm" onClick="totalSpent()">
<br>
<h2 id="youSpent"> Total Spent Today: