使用回撥函式和 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP