【发布时间】:2020-08-28 21:07:44
【问题描述】:
如果帐户类型为“储蓄”,我将尝试获取帐户余额的总和。我的想法是使用 forEach 循环遍历数组,然后如果帐户类型是储蓄,但不确定为什么它不起作用。
const accounts = [
{acctNo: 123, type: 'Checking', balance: 150},
{acctNo: 234, type: 'Checking', balance: 200},
{acctNo: 345, type: 'Savings', balance: 550},
{acctNo: 456, type: 'Checking', balance: 550},
{acctNo: 567, type: 'Savings', balance: 1500}
];
const sum = accounts.forEach(function(account){
if (account.type=== 'Savings'){
account.reduce(function(a,b){
return {balance: a.balance + b.balance}
})
}
})
console.log(sum)
【问题讨论】:
-
你的代码有很多问题——但最根本的是,你把它复杂化了。您只需要将
filter输入到帐户类型为Savings、map的帐户中,然后才执行总和(使用reduce或使用forEach的总和,无论您喜欢哪个)。
标签: javascript arrays iterator