使用遞迴在 JavaScript 中找出陣列的乘積


我們需要編寫一個 JavaScript 函式,它接收一個整數陣列。我們的函式應該執行以下兩件事 −

  • 使用遞迴方法。

  • 計算陣列中所有元素的乘積。

最後,它應該返回乘積。

例如 −

如果輸入陣列是 −

const arr = [1, 3, 6, .2, 2, 5];

那麼輸出應該是 −

const output = 36;

例子

這部分的程式碼為 −

const arr = [1, 3, 6, .2, 2, 5];
const arrayProduct = ([front, ...end]) => {
   if (front === undefined) {
      return 1;
   };
   return front * arrayProduct(end);
};
console.log(arrayProduct(arr));

輸出

控制檯中的輸出為 −

36

更新時間: 2020-11-24

544 次瀏覽

開啟您的 “職業生涯”

完成課程以獲得認證

開始
廣告
© . All rights reserved.