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

更新於: 10-Oct-2020

781 人閱讀

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.