支持谷歌、火狐、ie9以上等主流瀏覽器數組
array.reduce(function(prev, current, currentIndex, arr), initialValue)
初始值爲數值:瀏覽器
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const sum = arr.reduce(function (prev, current) { return prev+current }, 0) console.log(sum) //55
reduce根據函數傳進來的初始值,不斷回調疊加最終算出數組的和函數
初始值爲對象:code
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const sum = arr.reduce(function (prev, current) { prev.count = prev.count+current return prev }, {count: 0}) console.log(sum) //{count: 55}
若是初始值爲對象的話,返回的也是一個對象對象
初始值爲數組:索引
const str = 'hello' const newstr = str.split('').reduce(function (prev, current) { const obj = {}; obj[current] = current; prev.push(obj) return prev; }, []) console.log(newstr)
結果爲:回調函數
[{ h: 'h' },{ e: 'e' },{ l: 'l' },{ l: 'l' },{ o: 'o' }]
若是初始值爲數組,則返回的也是數組it
reduce應用:io
{ function func1(a) { return a*10; } function func2(b) { return b*2 } const test1 = func1(2) const test2 = func2(test1) console.log(test2) //40 }
這裏咱們須要先執行方法func1再根據func1返回的值,而後執行方法func2,咱們有時候會碰到不止兩個方法一塊兒,若是是多個呢,這個時候就要用到reduce來處理了console
function func1(a) { return a*10; } function func2(b) { return b*2 } function func3(c) { return c/2; } const compose = (...func) => (...init) => { if(func.length >= 2){ return func.reduce((prev, curr)=>{ prev = curr(prev) return prev; }, ...init) } return func(...init); } const a1 = compose(func1,func2)(2); console.log(a1) //40 const a2 = compose(func1,func2,func3)(2); console.log(a2) //20