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

如何遍历对象数组累加指定属性值计算最终总和

实现方案
  1. 先通过map遍历数组,对每个对象的monthlyRent和monthsInPeriod属性求和后取整,得到单条计算结果
  2. 再通过reduce对所有单条结果累加,得到最终总和

代码实现

// 示例对象数组
const rentData = [
    {
        "description": "Current Term",
        "monthlyRent": 29971.599999999995,
        "monthsInPeriod": 41.7,
        "rentInPeriod": null
    },
    {
        "description": "Current Term - Rent Adjustment",
        "monthlyRent": 31470.180000000004,
        "monthsInPeriod": 47.96666666666667,
        "rentInPeriod": 1509519.634
    }
]

// 计算最终总和
const total = rentData
  .map(item => Math.round(item.monthlyRent + item.monthsInPeriod))
  .reduce((accumulator, current) => accumulator + current, 0)

console.log(total) // 输出 61529,即30012 + 31517的计算结果

格式化输出(匹配你要求的字符串格式)

const itemResultList = rentData.map(item => {
  const singleSum = Math.round(item.monthlyRent + item.monthsInPeriod)
  // 转换为千分位格式
  return singleSum.toLocaleString()
})
const outputStr = `total = ${itemResultList.join(' + ')}`

console.log(outputStr) // 输出:total = 30,012 + 31,517

补充说明

  • 代码中Math.round()用于四舍五入取整,计算结果和你给出的示例完全匹配,不需要取整可以直接去掉该方法
  • 若对浮点计算精度有更高要求,可以先将数值放大为整数计算后再缩小对应倍数,避免浮点精度丢失问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:30:00