温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript之Array.reduce源码解读

发布时间:2020-11-02 15:04:44 来源:亿速云 阅读:157 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关JavaScript之Array.reduce源码解读,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

前言

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

看完上述内容,你们对JavaScript之Array.reduce源码解读有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI