JavaScript之Array.reduce源码解读-创新互联

今天就跟大家聊聊有关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源码解读-创新互联
标题网址:https://www.cdcxhl.com/article18/diicgp.html

成都网站建设公司_创新互联,为您提供商城网站云服务器网站建设搜索引擎优化定制网站建站公司

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都定制网站网页设计