JavaScript 中陣列的平方和與平方根和


問題

我們需要編寫一個 JavaScript 函式,該函式接受一個數組,其中包含多個數字。我們的函式應該遍歷該陣列中的每個數字,若它為偶數,則求其平方,若為奇數,則開平方,然後返回所有新數字的和,該和應四捨五入到小數點後兩位。

示例

以下是程式碼 -

 線上演示

const arr = [45, 2, 13, 5, 14, 1, 20];
const squareAndRootSum = (arr = []) => {
   const res = arr.map(el => {
      if(el % 2 === 0){
         return el * el;
      }else{
         return Math.sqrt(el);
      };
   });
   const sum = res.reduce((acc, val) => acc + val);
   return sum;
};
console.log(squareAndRootSum(arr));

輸出

613.5498231854631

更新於: 2021 年 4 月 19 日

354 次瀏覽

開啟你的職業

透過完成該課程獲得認證

開始
廣告