You need to enable JavaScript to run this app. 如何遍历对象数组并计算withdrawals数组的总和存入新数组?
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历对象数组并计算withdrawals数组的总和存入新数组?

银行账户取款总额计算方案

你的原代码当前只是把整个withdrawals数组直接存入结果,没有对数组内的金额求和。要实现需求,确实需要内部循环(或者用数组API简化实现),下面是两种可行的修改方案:

方案一:嵌套for循环实现

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

function getAllWithdrawals(bankAccounts) {
  let newArr = [];
  for (let acc of bankAccounts) {
    if (acc.withdrawals) {
      // 初始化取款总额变量
      let withdrawalTotal = 0;
      // 内部循环遍历取款数组累加金额
      for (let amount of acc.withdrawals) {
        withdrawalTotal += amount;
      }
      newArr.push(withdrawalTotal);
    } else {
      // 无取款数组则存入0
      newArr.push(0);
    }
  }
  return newArr;
}

// 调用测试
console.log(getAllWithdrawals(bankAccounts)); 
// 输出: [300.68, 0, 5900, 0, 100]

方案二:用数组API简化代码(更简洁)

利用map遍历账户数组,结合reduce对取款数组求和,代码更紧凑:

function getAllWithdrawals(bankAccounts) {
  return bankAccounts.map(acc => {
    // 存在取款数组则求和,否则返回0
    return acc.withdrawals 
      ? acc.withdrawals.reduce((sum, amount) => sum + amount, 0) 
      : 0;
  });
}

关键说明

  • 你猜想的没错,必须遍历每个账户的withdrawals数组才能完成求和,嵌套循环是最基础的实现方式。
  • reduce是数组内置的累加工具:第一个参数是累加函数(每次把当前金额加到总和里),第二个参数0是累加初始值,能确保即使取款数组为空也返回0(避免报错)。
  • map方法会自动生成新数组,不需要手动维护newArr,代码更简洁易读。

内容的提问来源于stack exchange,提问作者OldsoulPhil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:20:38