詳解JavaScript之Array.reduce源碼解讀
前言
reduce(...)方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個返回值(累計作用)
此方法接受兩個參數(shù):callback(...)(必選)、initialValue(可選)。callback(...)接受4個參數(shù):Accumulator (acc) (累計器)、Current Value (cur) (當(dāng)前值)、Current Index (idx) (當(dāng)前索引)、Source Array (src) (源數(shù)組)。
注意點:1、callback(...)一般需要返回值2、不會改變原數(shù)組
實現(xiàn)思路1、先獲取初始累計的值(分成兩種情況:有提供initialValue || 未提供initialValue)2、遍歷數(shù)組并執(zhí)行callback(...)3、返回累計值
源碼實現(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ù)組的第一個有效元素 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時 k=0 // accumulator=數(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)!
相關(guān)文章:
1. PHP使用Swagger生成好看的API文檔2. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進(jìn)度條3. Python3 json模塊之編碼解碼方法講解4. Python 制作查詢商品歷史價格的小工具5. Python 如何調(diào)試程序崩潰錯誤6. Python 利用Entrez庫篩選下載PubMed文獻(xiàn)摘要的示例7. ASP基礎(chǔ)知識VBScript基本元素講解8. python使用jenkins發(fā)送企業(yè)微信通知的實現(xiàn)9. Python sublime安裝及配置過程詳解10. Python 合并拼接字符串的方法

網(wǎng)公網(wǎng)安備