gpt4 book ai didi

javascript - 通过提交按钮输入到同一数组的所有值的总和

转载 作者:行者123 更新时间:2023-12-02 23:24:26 25 4
gpt4 key购买 nike

我认为下一步会很简单,但我一直在绞尽脑汁试图弄清楚。我输入了一笔花费并通过提交按钮输入。当我输入多个值时(因为我还列出了钱花在哪里),我试图获得所有花的钱的总数,但我要么得到 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>

最佳答案

这是我的 friend ,我做了最小的更改以使您的代码正常工作:

  1. 将数组初始化移至totalSpent() 之外
  2. 仅执行一次array.push(spent),无需循环
  3. 将初始值 0 添加到 array.reduce

  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>

关于javascript - 通过提交按钮输入到同一数组的所有值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com