网络编程 
首页 > 网络编程 > 浏览文章

详解JavaScript之Array.reduce源码解读

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

前言

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
官方规范

上一篇:uniapp电商小程序实现订单30分钟倒计时
下一篇:微信小程序实现星星评分效果
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网