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

JavaScript中数值相减未得预期负值问题排查

问题原因与修复方案

原因分析

你代码里的核心问题出在运算逻辑上:
每个el.amount的值都是负数(比如-100、-200),而你写的是total = total - el.amount——减去一个负数等于加上它的绝对值。

举个循环过程的例子:

  • 第一次循环:0 - (-100) = 100
  • 第二次循环:100 - (-200) = 300
  • 第三次循环:300 - (-400) = 700
    最终得到的自然是正数700,和你预期的求和结果完全相反。

修复方法

有两种简单的修复方式:

  1. 把减号改成加号,直接累加所有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
  1. 使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:33:10