数据加和,使用递归遍历,对任何的子嵌套都有用
let company = {
sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 600 }],
development: {
sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
internals: [{name: 'Jack', salary: 1300 }]
}
};
//用来完成工作的函数
function sumSalaries(department) {
if (Array.isArray(department)) {
//prev 加和后的值, current当前值
return department.reduce((prev, current) => prev + current.salary, 0); //求数组的和
} else {
let sum = 0;
for (let subdep of Object.values(department)) {
//Object.values 取对象的值
sum += sumSalaries(subdep); //递归调用子对象,对结果求和
}
return sum;
}
}
alert(sumSalaries(company)); //6700
网友评论