网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

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源码解读-创新互联
文章起源:http://bjjierui.cn/article/diicgp.html

其他资讯