亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

詳解JavaScript之Array.reduce源碼解讀

瀏覽:105日期:2023-10-09 14:43:50

前言

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

到此這篇關于詳解JavaScript之Array.reduce源碼解讀的文章就介紹到這了,更多相關JavaScript Array.reduce源碼內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 久久草在线视频免费 | 亚洲一级片在线播放 | 成熟亚洲妇女毛茸茸的性画廊 | 黄色成人影院 | 制服丝袜国产在线 | 国产成人精品日本亚洲专区6 | 午夜爱爱毛片xxxx视频免费看 | 免费观看好看的国产片 | 国产精品精品国产一区二区 | 一97日本道伊人久久综合影院 | 亚洲日韩欧美一区二区在线 | 亚洲理论在线观看 | av在线看网址 | 在线观看网址入口2020国产 | 国产成人综合一区精品 | 欧美人成在线观看 | 免费人成网址在线观看国内 | 波多野结衣黑人系列在线观看 | 国产精品久久久久这里只有精品 | 国产91精品黄网在线观看 | 国产精品青草久久久久婷婷 | 亚洲国产第一区二区香蕉 | 国内久久久久影院精品 | 亚洲 欧美 日韩在线综合福利 | 色婷婷丁香六月 | 亚洲自偷自偷首页 | 8mav福利视频在线播放 | 又硬又大又湿又紧a视频 | 1000部拍拍拍18勿入免费凤凰福利 | 亚洲不卡免费视频 | 91福利视频合集 | 成熟亚洲妇女毛茸茸的性画廊 | 毛茸茸年轻成熟亚洲人 | 中文字幕a∨在线乱码免费看 | 正在播放一区 | 日韩成人高清 | 国产在线视频自拍 | 欧美国产黄色 | 国产精品天天看特色大片不卡 | 成年午夜性爽快免费视频不卡 | 91精品福利手机国产在线 |