如何在数组中循环遍历对象并在 JavaScript 中汇总一项属性
假设我们有一个像这样的对象数组 −
const arr = [
{
duration: 10,
any: 'fields'
}, {
duration: 20,
any: 'other fields'
}, {
duration: 15,
any: 'some other fields'
}
];我们要求写一个 JavaScript 函数,它将这种数组作为输入,并返回所有目标的 duration 属性的总和结果。
对于上述数组,输出应为 45。
范例
代码如下 −
const arr = [
{
duration: 10,
any: 'fields'
}, {
duration: 20,
any: 'other fields'
}, {
duration: 15,
any: 'some other fields'
}
];
const addDuration = arr => {
let res = 0;
for(let i = 0; i < arr.length; i++){
res += arr[i].duration;
};
return res;
};
console.log(addDuration(arr));输出
控制台中的输出 −
45
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP