You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:05:23