JavaScript中数值相减未得预期负值问题排查
问题原因与修复方案
原因分析
你代码里的核心问题出在运算逻辑上:
每个el.amount的值都是负数(比如-100、-200),而你写的是total = total - el.amount——减去一个负数等于加上它的绝对值。
举个循环过程的例子:
- 第一次循环:
0 - (-100) = 100 - 第二次循环:
100 - (-200) = 300 - 第三次循环:
300 - (-400) = 700
最终得到的自然是正数700,和你预期的求和结果完全相反。
修复方法
有两种简单的修复方式:
- 把减号改成加号,直接累加所有
amount的值:
const my_transactions = [{amount: -100,currency: 'EUR'},{amount: -200,currency: 'EUR'},{amount: -400,currency: 'EUR'}]; let total = 0; my_transactions.forEach(el => total = total + el.amount); console.log('total:',total); // 输出 -700
- 使用
reduce方法(更符合数组求和的简洁写法):
const my_transactions = [{amount: -100,currency: 'EUR'},{amount: -200,currency: 'EUR'},{amount: -400,currency: 'EUR'}]; const total = my_transactions.reduce((sum, item) => sum + item.amount, 0); console.log('total:',total); // 输出 -700
内容的提问来源于stack exchange,提问作者oderfla
相关产品推荐
相关产品推荐

