如何在陣列中迴圈遍歷物件並在 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