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

您的位置:首頁技術(shù)文章
文章詳情頁

詳解JavaScript之Array.reduce源碼解讀

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

前言

reduce(...)方法對數(shù)組中的每個(gè)元素執(zhí)行一個(gè)由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個(gè)返回值(累計(jì)作用)

此方法接受兩個(gè)參數(shù):callback(...)(必選)、initialValue(可選)。callback(...)接受4個(gè)參數(shù):Accumulator (acc) (累計(jì)器)、Current Value (cur) (當(dāng)前值)、Current Index (idx) (當(dāng)前索引)、Source Array (src) (源數(shù)組)。

注意點(diǎn):1、callback(...)一般需要返回值2、不會(huì)改變原數(shù)組

實(shí)現(xiàn)思路1、先獲取初始累計(jì)的值(分成兩種情況:有提供initialValue || 未提供initialValue)2、遍歷數(shù)組并執(zhí)行callback(...)3、返回累計(jì)值

源碼實(shí)現(xiàn)

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=數(shù)組的第一個(gè)有效元素 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’); } } // 當(dāng)accumulator=initialValue時(shí) k=0 // accumulator=數(shù)組的第一個(gè)有效元素時(shí) 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 官方規(guī)范

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

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 日本一区精品久久久久影院 | 欧洲第一区第二区第三区 | 韩日免费视频 | 国产精品视频网址 | 久久99精品综合国产首页 | 日韩一区二区三区视频在线观看 | 黄色视屏免费在线观看 | 国产肥老妇视频69 | 国产欧美日韩视频在线观看一区二区 | 精品日韩欧美一区二区三区 | 国产精品1024永久观看 | 日本aaaaa高清免费看 | 中文日韩欧美 | 久久国产成人福利播放 | 九九精品免视频国产成人 | 色屁屁www欧美激情在线观看 | 成 人免费va视频 | 国产日韩欧美在线观看播放 | 国产香蕉久久 | 欧美日韩中文国产一区二区三区 | 欧美一区二区三区不卡免费观看 | 国产成人精品免费久久久久 | 亚洲 欧美 激情 另类 校园 | 青青青在线观看视频免费播放 | 国产欧美日本在线观看 | 大美女久久久久久j久久 | 欧美午夜理伦三级在线观看 | 九九草在线观看 | 黑人巨茎xxx免费视频 | 黄色录像一级带 | 国产亚洲蜜芽精品久久 | 亚洲精品在线免费观看视频 | 亚洲综合色视频 | 四月色| 中国国产一国产一级毛片视频 | 成人国产在线不卡视频 | 韩国19禁青草福利视频在线 | 免费在线a | 亚洲免费福利 | 制服亚洲 | 亚洲图区综合 |