国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Javascript數(shù)組方法reduce的妙用之處分享

2024-05-06 15:38:11
字體:
供稿:網(wǎng)友

前言

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:// ]            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 修武县| 古交市| 绥德县| 溆浦县| 客服| 农安县| 永宁县| 介休市| 如皋市| 青阳县| 时尚| 东安县| 榆社县| 应用必备| 天津市| 上饶县| 汉源县| 将乐县| 苏尼特左旗| 乌什县| 油尖旺区| 民勤县| 亳州市| 大余县| 侯马市| 永福县| 木里| 通榆县| 蒲江县| 岳池县| 沙湾县| 克东县| 永和县| 梁平县| 墨江| 崇义县| 沙湾县| 台州市| 惠东县| 夏河县| 比如县|