在 JavaScript 中使用回调函数和初始值积累一些值
问题
我们需要编写一个JavaScript函数,该函数接受一个数组、一个回调函数和一个初始值。
该函数应该在数组的迭代中累积一个值,并最终像数组一样返回该值。做。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
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话