国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

詳解JavaScript之Array.reduce源碼解讀

瀏覽:88日期: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
相關文章:
主站蜘蛛池模板: 湟中县| 铁岭市| 泽普县| 乌拉特后旗| 永州市| 乳山市| 攀枝花市| 沽源县| 柳州市| 海阳市| 龙井市| 德阳市| 洮南市| 钟山县| 乌兰察布市| 祁连县| 康平县| 磐安县| 同江市| 西青区| 满洲里市| 阳信县| 湖口县| 北辰区| 自治县| 孟津县| 福海县| 内乡县| 锡林郭勒盟| 定州市| 兴文县| 特克斯县| 宁津县| 秦安县| 来安县| 屏南县| 阜宁县| 方山县| 潞城市| 高碑店市| 凉城县|