詳解JavaScript之Array.reduce源碼解讀
前言
reduce(...)方法對(duì)數(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ì)改變?cè)瓟?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; // 分成兩種情況來(lái)獲取accumulator // 有提供initialValue accumulator=initialValue // 沒(méi)有提供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
參考鏈接:
到此這篇關(guān)于詳解JavaScript之Array.reduce源碼解讀的文章就介紹到這了,更多相關(guān)JavaScript Array.reduce源碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用js操作css實(shí)現(xiàn)js改變背景圖片示例
有個(gè)朋友在weibo上問(wèn)我可不可以用JS和CSS讓頁(yè)面每次刷新隨機(jī)產(chǎn)生一張背景圖,當(dāng)然是可以的。具體的方法看下面的實(shí)現(xiàn)代碼吧2014-03-03js實(shí)現(xiàn)視圖和數(shù)據(jù)雙向綁定的方法分析
這篇文章主要介紹了js實(shí)現(xiàn)視圖和數(shù)據(jù)雙向綁定的方法,結(jié)合實(shí)例形式分析了vue.js及jQuery數(shù)據(jù)綁定相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2020-02-02javascript下使用Promise封裝FileReader
這篇文章主要介紹了javascript下使用Promise封裝FileReader,需要的朋友可以參考下2016-02-02IE8 兼容性問(wèn)題(屬性名區(qū)分大小寫(xiě))
屬性名大小寫(xiě)問(wèn)題,如屬性window.screen.height2009-06-06JavaScript?內(nèi)置對(duì)象?BigInt詳細(xì)解析
這篇文章主要介紹了JavaScript?內(nèi)置對(duì)象?BigInt詳細(xì)解析,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07