大家好,我是CUGGZ。在JavaScript中,reduce是最难理解的数组方法之一。它是一个强大而灵活的高阶函数。一起来看看reduce的神奇吧!1.基本用法reduce()是JavaScript中一个非常有用的数组方法。MDN是这样解释的:reduce()方法对数组中的每个元素按顺序执行一个reducer函数,每次reducer运行时,将前一个元素的计算结果作为参数传入,最后将它们的结果聚合起来成一个单一的返回值。reduce()方法的语法如下:array.reduce(reducer,initialValue)有两个参数:(1)reducer函数包含四个参数:previousValue:上次调用callbackFn时的返回值。第一次调用时,如果指定了初始值initialValue,则其值为initialValue,否则为数组索引为0的元素array[0]。currentValue:正在处理的数组中的元素。第一次调用时,如果指定了初始值initialValue,则其值为数组索引为0的元素array[0],否则为array[1]。currentIndex:正在处理的数组中元素的索引。如果指定了初始值initialValue,则起始索引号为0,否则从索引1开始。array:要遍历的数组。(2)initialValue作为参数previousValue的值可选,第一次调用回调函数时。如果指定了initialValue,则currentValue将使用数组的第一个元素;否则previousValue将使用数组的第一个元素,currentValue将使用数组的第二个元素。以下是使用reduce()求数组元素之和的示例:constarr=[0,1,2,3,4];constcalculateSum=(previousValue,currentValue)=>{console.log('previousValue:',previousValue);console.log('currentValue:',currentValue);returnpreviousValue+currentValue;};arr.reduce(calculateSum)reducer会逐个遍历数组元素,每一步比较当前元素的值和上一步的计算结果Add(上一步的计算结果是当前元素之前所有元素的总和),直到不再添加元素。这段代码的输出结果如下:执行过程如下:当我们给reduce()方法一个初始值12时:arr.reduce(calculateSum,12);执行过程如下:如果数组为空且没有提供初始值,reduce()方法会抛出TypeError:constreducer=(accumulator,currentValue)=>accumulator+currentValue;constresult=[].reduce(reducer)console.log(result)输出结果如下:二、使用技巧(1)数组求和reduce()方法最直接的用法就是对数组元素求和:const总计=[34,12,143,13,76].reduce((previousValue,currentValue)=>previousValue+currentValue,0);console.log(total);输出结果如下:278(2)flatarrayreduce()方法也可以将数组展平:constarray=[[0,1],[2,3],[4,5],[5,6]];constflattenedArray=array.reduce((previousValue,currentValue)=>previousValue.concat(currentValue),[]);console.log(flattenedArray);输出结果如下:[0,1,2,3,4,5,5,6]如果数组嵌套不止一层,可以递归调用reduce函数将它们拼平,然后拼接他们与最终的阵列。constnestedArray=[[1,[2,3]],[4,5],[[6,7],[8,9]]];函数flattenArray(nestedArray){返回nestedArray。reduce((累加器,currentValue)=>accumulator.concat(Array.isArray(currentValue)?flattenArray(currentValue):currentValue),[]);}constflattenedArray=flattenArray(nestedArray);console.log(flattenedArray)输出结果如下:[1,2,3,4,5,6,7,8,9](3)数组分组假设有一个国家对象数组,将每个国家分组根据国家所在的大陆排列。这可以使用reduce方法来完成:cosntcountries=[{name:"Germany",continent:"Europe"},{name:"Brazil",continent:"SouthAmerica"},{name:"India",continent:"Asia"},{name:"France",continent:"Europe"},{name:"SouthKorea",continent:"Asia"},]constgroupedCountries=国家。reduce((groupedCountries,country)=>{if(!groupedCountries[country.continent]){groupedCountries[country.continent]=[]}groupedCountries[country.continent].push(country)返回groupedCountries},{});console.log(groupedCountries)的输出如下:(4)使用reduce()代替filter().map()在Javascript中,数组的filter方法可以通过回调过滤数组中的元素,并且map方法可以通过回调内部传递的逻辑使用旧数组创建新数组。有时我们必须同时使用这两种方法来创建一个新的按某些条件过滤的结果数组。您可以使用reduce方法来完成同样的工作,这样您只需要遍历一次数组。例如,要创建大于30的数字的平方根数组,可以使用filter().map()编写:constnumbers=[3,21,34,121,553,12,53,5,42,11];constnewArray=numbers.filter(numbernumber>30).map(numberMath.sqrt(number));使用reduce实现:constnumbers=[3,21,34,121,553,12,53,5,42,11];constnewArray=numbers.reduce((previousValue,currentValue)=>{if(currentValue>30){previousValue.push(Math.sqrt(currentValue))}returnpreviousValue},[]);console.log(newArray);输出结果如下:[5.830951894845301,11,23.515952032609693,7.280109889280518,6.48074069840786](5)统计数组元素出现的次数可以使用reduce统计数组中每个元素出现的次数:constcolors=['绿色',','红色','黄色','红色','黄色','绿色','绿色'];常量colorMap=颜色。reduce((previousValue,currentValue)=>{previousValue[currentValue]>=1?previousValue[currentValue]++:previousValue[currentValue]=1;returnpreviousValue;},{});控制台日志(颜色映射);输出如下:{green:3,red:3,yellow:2}(6)SerialExecution异步函数有一组异常需要串行执行step函数,可以使用reduce()调用执行:constfunctions=[asyncfunction(){return1;},异步函数(){返回2;},异步函数(){返回3;}];constres=awaitfunctions.reduce((promise,fn)=>promise.then(fn),Promise.resolve());控制台日志(资源);//outputresult:3其中res相当于execution:Promise.解决()。然后(fn1)。然后(fn2)。然后(fn3);(7)创建管道假设有一组简单的数学函数可以让我们增加、减少、加倍和减半:functionincrement(input){returninput+1;}functiondecrement(input){returninput—1;}functiondouble(input){返回输入*2;}functionhalve(input){返回输入/2;一旦执行了上述操作,reduce()管道就是用于将一些初始值转换为最终值的函数列表的术语。我们只需要将执行过程中每一步用到的函数写在pipeline数组中即可。constpipeline=[递增,双倍,递减];constresult=pipeline.reduce((total,func)=>{returnfunc(total);},5);console.log(result)//outputresult:11(8)要反转字符串,可以使用reduce()反转字符串:conststr='helloworld';[...str].reduce((a,v)=>v+a);//outputResult:'dlrowolleh'(9)数组去重有一个数组有重复项,可以使用reduce()对数组进行去重:constarr=["
