您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關JavaScript之Array.reduce源碼解讀,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
前言
reduce(...)方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結果匯總為單個返回值(累計作用)
此方法接受兩個參數(shù):callback(...)(必選)、initialValue(可選)。
callback(...)接受4個參數(shù):Accumulator (acc) (累計器)、Current Value (cur) (當前值)、Current Index (idx) (當前索引)、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'); } } // 當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
看完上述內(nèi)容,你們對JavaScript之Array.reduce源碼解讀有進一步的了解嗎?如果還想了解更多知識或者相關內(nèi)容,請關注億速云行業(yè)資訊頻道,感謝大家的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。