使用回撥函式和 JavaScript 中的初始值累加一些值


問題

我們需要編寫一個 JavaScript 函式,它接收一個數組、一個回撥函式和一個初始值。

該函式應在陣列的迭代中累加一個值,最終返回該值,就像 Array.prototype.reduce() 所做的那樣。

示例

程式碼如下 −

 演示

const arr = [1, 2, 3, 4, 5];
const sum = (a, b) => a + b;
Array.prototype.customReduce = function(callback, initial){
   if(!initial){
      initial = this[0];
   };
   let res = initial;
   for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){
      res = callback(res, this[i]);
   };
   return res;
};
console.log(arr.customReduce(sum, 0));

輸出

控制檯輸出如下 −

15

更新於: 17-04-2021

175 次瀏覽

啟動 職業生涯

完成課程,獲取認證

開始
廣告