详解JavaScript之Array.reduce源码解读
前言
reduce(...)方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值(累计作用)
此方法接受两个参数:callback(...)(必选)、initialValue(可选)。
callback(...)接受4个参数:Accumulator(acc)(累计器)、CurrentValue(cur)(当前值)、CurrentIndex(idx)(当前索引)、SourceArray(src)(源数组)。
注意点:
1、callback(...)一般需要返回值
2、不会改变原数组
实现思路
1、先获取初始累计的值(分成两种情况:有提供initialValue||未提供initialValue)
2、遍历数组并执行callback(...)
3、返回累计值
源码实现
Array.prototype.myReduce=function(callback,initialValue){
if(this===null){
thrownewTypeError('Array.prototype.reducecalledonnullorundefined');
}
if(typeofcallback!=='function'){
thrownewTypeError(callback+'isnotafunction');
}
constO=Object(this);
constlenValue=O.length;
constlen=lenValue>>>0;
if(len===0&&!initialValue){
thrownewTypeError('thearraycontainsnoelementsandinitialValueisnotprovided');
}
letk=0;
letaccumulator;
//分成两种情况来获取accumulator
//有提供initialValueaccumulator=initialValue
//没有提供initialValueaccumulator=数组的第一个有效元素
if(initialValue){
accumulator=initialValue;
}else{
letkPressent=false;
while(!kPressent&&k
参考链接:
reduce-mdn
官方规范
到此这篇关于详解JavaScript之Array.reduce源码解读的文章就介绍到这了,更多相关JavaScriptArray.reduce源码内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!