今天就跟大家聊聊有關(guān)JavaScript之Array.reduce源碼解讀,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

前言
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;
// 分成兩種情況來獲取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
本文題目:JavaScript之Array.reduce源碼解讀-創(chuàng)新互聯(lián)
標(biāo)題網(wǎng)址:http://chinadenli.net/article18/diicgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、云服務(wù)器、網(wǎng)站建設(shè)、搜索引擎優(yōu)化、定制網(wǎng)站、建站公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容