如何在 JavaScript 中迭代数组中的对象并求和属性
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/19 4:28:17
假设我们有一个像这样的对象数组 −
const arr = [
{
duration: 10,
any: 'fields'
}, {
duration: 20,
any: 'other fields'
}, {
duration: 15,
any: 'some other fields'
}
];
我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组并返回所有对象的持续时间属性的总和结果。
对于上述数组,输出应为 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

