详解JavaScript之Array.reduce源码解读
#代码知识 发布时间: 2026-01-12
前言

reduce(...)方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值(累计作用)
此方法接受两个参数:callback(...)(必选)、initialValue(可选)。
callback(...)接受4个参数:Accumulator (acc) (累计器)、Current Value (cur) (当前值)、Current Index (idx) (当前索引)、Source Array (src) (源数组)。
注意点:
1、callback(...)一般需要返回值
2、不会改变原数组
实现思路
1、先获取初始累计的值(分成两种情况:有提供initialValue || 未提供initialValue)
2、遍历数组并执行callback(...)
3、返回累计值
源码实现
Array.prototype.myReduce = function(callback, initialValue) {
if(this === null) {
throw new TypeError( 'Array.prototype.reduce called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback + ' is not a function');
}
const O = Object(this);
const lenValue = O.length;
const len = lenValue >>> 0;
if(len === 0 && !initialValue) {
throw new TypeError('the array contains no elements and initialValue is not provided');
}
let k = 0;
let accumulator;
// 分成两种情况来获取accumulator
// 有提供initialValue accumulator=initialValue
// 没有提供initialValue accumulator=数组的第一个有效元素
if(initialValue) {
accumulator = initialValue;
} else {
let kPressent = false;
while(!kPressent && k < len) {
const pK = String(k);
kPressent = O.hasOwnProperty(pK);
if(kPressent) {
accumulator = O[pK];
};
k++;
}
if(!kPressent) {
throw new TypeError('the array contains error elements');
}
}
// 当accumulator=initialValue时 k=0
// accumulator=数组的第一个有效元素时 k=1
while(k < len) {
if(k in O) {
// callback一般需要返回值
accumulator = callback(accumulator, O[k], k, O);
}
k++;
}
return accumulator;
}
let r = [1,2,3].myReduce(function (prevValue, currentValue, currentIndex, array) {
return prevValue + currentValue;
}, 22);
console.log(r); // 28
参考链接:
reduce-mdn
官方规范
上一篇 : 详解Anaconda安装tensorflow报错问题解决方法
下一篇 : C++代码实现逆波兰表达式
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!