前言
Javascript數(shù)組方法中,相比map、filter、forEach等常用的迭代方法,reduce常常被我們所忽略,今天一起來探究一下reduce在我們實戰(zhàn)開發(fā)當(dāng)中,能有哪些妙用之處,下面從reduce語法開始介紹。
語法
array.reduce(function(accumulator, arrayElement, currentIndex, arr), initialValue)
若傳入初始值,accumulator首次迭代就是初始值,否則就是數(shù)組的第一個元素;后續(xù)迭代中將是上一次迭代函數(shù)返回的結(jié)果。所以,假如數(shù)組的長度為n,如果傳入初始值,迭代次數(shù)為n;否則為n-1。
比如實現(xiàn)數(shù)組 arr = [1,2,3,4] 求數(shù)組的和
let arr = [1,2,3,4];arr.reduce(function(pre,cur){return pre + cur}); // return 10實際上reduce還有很多重要的用法,這是因為累加器的值可以不必為簡單類型(如數(shù)字或字符串),它也可以是結(jié)構(gòu)化類型(如數(shù)組或?qū)ο螅?,這使得我們可以用它做一些其他有用的事情,比如:
將數(shù)組轉(zhuǎn)換為對象 展開更大的數(shù)組 在一次遍歷中進(jìn)行兩次計算 將映射和過濾函數(shù)組合 按順序運行異步函數(shù)將數(shù)組轉(zhuǎn)化為對象
在實際業(yè)務(wù)開發(fā)中,你可能遇到過這樣的情況,后臺接口返回的數(shù)組類型,你需要將它轉(zhuǎn)化為一個根據(jù)id值作為key,將數(shù)組每項作為value的對象進(jìn)行查找。
例如:
const userList = [ { id: 1, username: 'john', sex: 1, email: 'john@163.com' }, { id: 2, username: 'jerry', sex: 1, email: 'jerry@163.com' }, { id: 3, username: 'nancy', sex: 0, email: '' }];如果你用過lodash這個庫,使用_.keyBy這個方法就能進(jìn)行轉(zhuǎn)換,但用reduce也能實現(xiàn)這樣的需求。
function keyByUsernameReducer(acc, person) { return {...acc, [person.id]: person};}const userObj = peopleArr.reduce(keyByUsernameReducer, {});console.log(userObj);將小數(shù)組展開成大數(shù)組
試想這樣一個場景,我們將一堆純文本行讀入數(shù)組中,我們想用逗號分隔每一行,生成一個更大的數(shù)組名單。
const fileLines = [ 'Inspector Algar,Inspector Bardle,Mr. Barker,Inspector Barton', 'Inspector Baynes,Inspector Bradstreet,Inspector Sam Brown', 'Monsieur Dubugue,Birdy Edwards,Inspector Forbes,Inspector Forrester', 'Inspector Gregory,Inspector Tobias Gregson,Inspector Hill', 'Inspector Stanley Hopkins,Inspector Athelney Jones'];function splitLineReducer(acc, line) { return acc.concat(line.split(/,/g));}const investigators = fileLines.reduce(splitLineReducer, []);console.log(investigators);// [// "Inspector Algar",// "Inspector Bardle",// "Mr. Barker",// "Inspector Barton",// "Inspector Baynes",// "Inspector Bradstreet",// "Inspector Sam Brown",// "Monsieur Dubugue",// "Birdy Edwards",// "Inspector Forbes",// "Inspector Forrester",// "Inspector Gregory",// "Inspector Tobias Gregson",// "Inspector Hill",// "Inspector Stanley Hopkins",// "Inspector Athelney Jones"http:// ]
新聞熱點
疑難解答
圖片精選