国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表

圖片精選

主站蜘蛛池模板: 牟定县| 舒城县| 自贡市| 保山市| 衡东县| 长治市| 九龙坡区| 久治县| 阜南县| 和平县| 霍城县| 乌苏市| 临沧市| 玛纳斯县| 湄潭县| 莱西市| 普陀区| 开远市| 西宁市| 扶风县| 高碑店市| 定日县| 漯河市| 喀什市| 陈巴尔虎旗| 盖州市| 吉隆县| 旬邑县| 华坪县| 江津市| 安福县| 内乡县| 长乐市| 临汾市| 南开区| 胶南市| 灌云县| 衡阳县| 莲花县| 赤水市| 信丰县|