只新增奇數或偶數的 JavaScript


我們需要編寫一個函式,給定一個數字陣列和一個字串,該字串可以取兩個值之一“奇數”或“偶數”,新增符合該條件的數字。如果沒有值符合條件,則應返回 0。

例如,−

console.log(conditionalSum([1, 2, 3, 4, 5], "even")); => 6
console.log(conditionalSum([1, 2, 3, 4, 5], "odd")); => 9
console.log(conditionalSum([13, 88, 12, 44, 99], "even")); => 144
console.log(conditionalSum([], "odd")); => 0

因此,讓我們編寫此函式的程式碼,我們將在此處使用 Array.prototype.reduce() 方法 −

示例

const conditionalSum = (arr, condition) => {
   const add = (num1, num2) => {
      if(condition === 'even' && num2 % 2 === 0){
         return num1 + num2;
      }
      if(condition === 'odd' && num2 % 2 === 1){
         return num1 + num2;
      };
      return num1;
   }
   return arr.reduce((acc, val) => add(acc, val), 0);
}
console.log(conditionalSum([1, 2, 3, 4, 5], "even"));
console.log(conditionalSum([1, 2, 3, 4, 5], "odd"));
console.log(conditionalSum([13, 88, 12, 44, 99], "even"));
console.log(conditionalSum([], "odd"));

輸出

控制檯中的輸出將為 −

6
9
144
0

更新於:2020-08-21

811 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.