Array.protype.reduce
reduce() 方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行)删掀,將其結(jié)果匯總為單個返回值假消。
-
callback
執(zhí)行數(shù)組中每個值 (如果沒有提供 initialValue則第一個值除外)的函數(shù)听系,包含四個參數(shù):- accumulator
累計器累計回調(diào)的返回值; 它是上一次調(diào)用回調(diào)時返回的累積值虑润,或initialValue(見于下方)肥荔。 - currentValue
數(shù)組中正在處理的元素。 - index 可選
數(shù)組中正在處理的當(dāng)前元素的索引宴咧。 如果提供了initialValue根灯,則起始索引號為0,否則從索引1起始悠汽。 - array可選
調(diào)用reduce()的數(shù)組
- accumulator
-
initialValue(可選)
作為第一次調(diào)用 callback函數(shù)時的第一個參數(shù)的值箱吕。 如果沒有提供初始值,則將使用數(shù)組中的第一個元素柿冲。 在沒有初始值的空數(shù)組上調(diào)用 reduce 將報錯茬高。
文檔鏈接
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
應(yīng)用1:數(shù)組求和
let d=[1,2,3,4,5];
var res=d.reduce((a,b)=>{
return a+b;
}.2); //13
源碼實(shí)現(xiàn)
Array.prototype._reduce=function(cb,defaultValue){
// debugger
if(!Array.isArray(this))
{
throw new TypeError('this is not array');
}
if(typeof cb!=='function')
{
throw new TypeError('no function');
}
if(this.length<2)
{
return defaultValue?defaultValue:null;
}
let arr=[...this],res=null;
//沒有初始值 取第一個假抄,數(shù)組長度也會減少1
res=defaultValue?defaultValue.shift();
//依次執(zhí)行
arr.map((item,index)=>res=cb(res,item,index,arr));
return res;
}
let d=[1,2,3,4,5]
d._reduce((a,b)=>{
return a+b;
})
//11