如何遍历对象数组累加指定属性值计算最终总和
实现方案
- 先通过
map遍历数组,对每个对象的monthlyRent和monthsInPeriod属性求和后取整,得到单条计算结果 - 再通过
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
相关产品推荐
相关产品推荐

