reduce()方法对数组中的每一个元素实行一个reducer函数(由你供给),然后得到一个单一的输出值。

reduce() 方法将一个数组中的全部元素还原成一个单一的输出值,输出值可以是数字、方针或字符串。 reduce() 方法有两个参数,第一个是回调函数,第二个是初始值

回调函数

回调函数在数组的每个元素上实行。回调函数的返回值是累加效果,并作为下一次调用回调函数的参 r v s B # }数供给。回调函数带有四个参数。

  • Accumulator(累加器)——累加器累加回调函数的返回值。
  • Current Value(其时值)——处理数组的其时元素。
  • Current Index(其时索引)——处理数组其时元素的索引。
  • Source Array(源数组)

Curren1 2 c 8t IndexSource Array是可选的。

初始值

假设指定了初始值,则将累加器设置为 i8 ( L = 1 enitim ( _ g / !alValue 作为初始元素。不然,将累加器设置为数组的第一个元素作为初始元素。

arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])

不才面3 Y Q g的代码片段中H Q o l,第一个累加器(accumulator)被分配了初始值0。currentValueN A m { 是正在处理的 numbersArr 数组的元素。在这儿,curre6 1 E 0 U 2 r OntValun A r d H K 7 $e 被增加到累加器,不才次调用回调函数时,会将返回值作为参数供给。

coY % l ;nst numbersArr = [67, 90,T m X % n G 100, 37, 60];
c? u @ t n ) 3 a Konst total = numbersArr.reduce(f= 3 A E  1 , { Bunction(accumulator, cu+ Y # D T WrrentValue){
console6 z P.log("accumulator is " + accumulator + " current valut y . 1 L ve is " + currentValue);
return accumulator + currentValue;
}, 0);
console` % U 7 ) * -.log("total : "+ tots D w B k C . tal);

输出

accumulator is 0 current value is 67
accumulato. q G r is 67 current value is 90
accumulator is 157 current value is 100
accumulator is 257 current value is 37
accumulator is 294 current value is 60
total : 354

JavaScript reduce用例

1.对数组T a X $ T 1的全部值求和

不才面的代码中,studentResul{ j j r I 8 # Z ,t 数组具有5个数字。运用, S R k ! C 6 reduce() 方法,将数组削减为单个值,该值将 studentResult 数组的全部值和效果分配给 total

const studentResult = [67, 90, 100, 37, 60];
const to5 , Ftal = stuo w r  $ c l k kdentResult.reduce((accumulator, currentValue) => accumulator +currentValue, 0);
console.log(total); // 354

2.方针数组中的数值之和

一般,我们从后端获取数据作为方针数组,因此,reduce() 方法有助于处理我们的前端逻辑M + E { b。不才( 7 @ 9 }面的代码a j x m J b中,studentResult 方针数组有三个科目,这儿,curr^ o Q r ` X n XentValue.marks 取了 studentResult 方针数组中每个科目的分数。

const studentResult = [
{ subject: '数学', marks: 78 },
{ subject: '物理',s X G S n X p marks: 80 },
{ subject: '_ ~ - O化学', marks: 93 }
];
const total = studentResul{ x  6t.reduce((ac$ M d m 0 S A p }cumulator, currentValue) => accumulator + currentValue.marks, 0);
co) K P 7 insole.log(total); // 251

3.展平数组

“展平数组”是指将多维数组转换为一维。不才面的代码中,twoDArr 2维数组被转换为 oneDArr 一维数组。i B ` z j Z U q S此处,第一个 [1,2] 数组分配给累加器 a: & 0 Uccumul. c D H F gator,然后 twoDArr 数组的其他每个元素都连接到累加器。

const twoDA* _ 4 3 6 Hrr = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ];
const oneDArr = twoDArr.reduce((accumulator, currentValue) =9 u l 8 u q | X 7> accumulator.c| M | G J % T ^oncat(currentValue));
cons_ q = H 5 0 $ole.log] + @ m(oneDArr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

4.按特色分组方针

根据方针的特色,我们可以运用 reduF | { 0ce() 方法将方针数组分为几组。通过下面的代码片段,你可以清楚Z ; p 9 & f x u地理解这个概念。这儿,result 方针数组有五个方针,每个方针都有 sut z R ~ q Ibjectmarks 特色。假设分数大于或等于50,则该主题通过,不然,主题失利。 reduceI A X() 用于将效果分组为通过和失利。首要,将 initialValue 分配给累加器,然后 push([ R Q ~ s k H [ j) 方法在检查条件之后将其时目t / o l标增加到 passfail 特色中作为方针数组。

const result = [
{subject: '物理', marks: 41},
{subject: '化学', marks: 59},
{subject: '高等数学', marks: 36},
{subject: '运用数学', marks: 90},
{subject: '英语', marks: 64},
];
let initialValue = {{ 1 d # U
pass: [],
fail: []
}
const groupedResult = result.reduce((accumulator, current) => {
(current.^ - - z z 4 V tmarks >= 50) ? accumulator.pass.push(current) : accumulator.fail.push(current);
return aG G sccumul[ d R $ a l Gator;
}, initialValue);
console.log(groupO $ I ~ T kedResul& E y @ |t);

输出

{
pass: [
{ subject: ‘化学’, marks: 59 },
{ subject: ‘运用数学’, marks: 90 },
{ subject: ‘英语’,z x Q z K s { marks: 64 }
],
fail: [
{ subject: ‘物理’, marks: 41c 1 4 X r B X @ },
{ subject: ‘高等数学’, marks: 36 }
]
}

5.删去数组中的重复项

不才面的代码片段中,删去了 pliU H g IcE | + y CatedArr 数组中的重复项。首要,将一个空数e # C 5 N w r# , e e H i 1 F分配给累加器作为初始值。accumulator.includes() 检查 duplicatedArr 数组的每个元素是否^ ~ w x c @已经在累加器中可用。假设 currentValue 在累加器中不可x S p c u `用,则运用 push() 将其增加。

const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7];
const removeDuplicatedArr = duplic[ s 6 * s aatedsArr.reduce((accumulator, currentValue) => {
if(!accumd M b p : Y 0 - Kulator.includes(currentVD : c ` 5 K /alue)){
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(removeDuplicateJ 5 .dArr);
// [ 1, 5, 6, 7, 8, 9 ]

总结

在本文中,我们评论2 y 6 D了数组 reduce() 方法。首要介绍 reduce() 方法,然后,运用一个简单的示例评论其行为。最终,通过示例评论了 reduce() 方法最常见的五个用例。假设你是JavaScript的初学者,那么本文将对你有所帮助。


来历:medium.com/javascript-…,作者:waA j Ythsala danthasinghe,翻译:大众号《前端全栈开发者》

JavaScript中的reduce()的5个用例