JavaScript实现不限次数输入数字累加求和功能求助
解决方案
不用数组的话,有两种简单的实现方式,核心都是持续维护累加的总和:
方式一:全局变量存储总和
在script.js中写入以下代码:
let totalSum = 0; function add() { const priceInput = document.getElementById('n1'); const totalInput = document.getElementById('n2'); // 把输入值转为数字,空值或非数字默认按0处理 const currentPrice = parseFloat(priceInput.value) || 0; totalSum += currentPrice; totalInput.value = totalSum; // 清空输入框方便下次输入 priceInput.value = ''; }
关键说明:
- 全局变量
totalSum会持续保存累加的总和,不会因为函数执行结束被销毁 parseFloat确保输入的字符串转为数字,|| 0处理用户输入为空、非有效数字的情况,避免出现NaN错误
方式二:利用总计输入框存储当前总和
如果不想用全局变量,可以直接从禁用的总计输入框中读取当前总和进行累加:
function add() { const priceInput = document.getElementById('n1'); const totalInput = document.getElementById('n2'); const currentPrice = parseFloat(priceInput.value) || 0; // 读取当前总计值,初始为空则按0计算 const currentTotal = parseFloat(totalInput.value) || 0; const newTotal = currentTotal + currentPrice; totalInput.value = newTotal; priceInput.value = ''; }
关键说明:
- 不需要额外的全局变量,直接复用页面上的总计输入框存储状态
- 同样需要用
parseFloat转换字符串值为数字,避免字符串拼接错误
内容的提问来源于stack exchange,提问作者Res
相关产品推荐
相关产品推荐

