前言
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
官方规范
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“详解JavaScript之Array.reduce源码解读”评论...
更新动态
2025年10月24日
2025年10月24日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]