。map()。filter()。reduce()的用法(转载
原文链接:https:www。jianshu。compe87b195f6943。map()
让我用一些简单的例子来解释它是如何工作的。如果说你收到一组包含多个对象的数组,每个对象是一个person。最终你只希望得到一个只包含id的数组。Whatyouhavevarofficers〔{id:20,name:CaptainPiett},{id:24,name:GeneralVeers},{id:56,name:AdmiralOzzel},{id:88,name:CommanderJerjerrod}〕;Whatyouneed〔20,24,56,88〕
我想你有多种方式来实现这个目标:。forEach(),。for(。。。of),或者一个简单的。for()
让我们对比一下吧!
用。forEach()varofficersIds〔〕;officers。forEach(function(officer){officersIds。push(officer。id);});
可以注意到,你不得不先创建一个空数组?让我们来看看。map()是如何做到的。varofficersIdsofficers。map(function(officer){returnofficer。id});
我们可以使用箭头函数做到更加的精简。constofficersIdsofficers。map(officerofficer。id);
那么。map()是怎么运行的呢?实际上对数组的每个元素都遍历一次,同时返回一个新的值。记住一点是返回的这个数据的长度和原始数组长度是一致的。。filter()
假如你有一个数组,你只想要这个数组中的一些元素怎么办呢?这时候。filter()就非常好用了。varpilots〔{id:2,name:WedgeAntilles,faction:Rebels,},{id:8,name:CienaRee,faction:Empire,},{id:40,name:IdenVersio,faction:Empire,},{id:66,name:ThaneKyrell,faction:Rebels,}〕;
如果我们现在想要两个数组:一个是rebel飞行员,一个是imperials飞行员,用。filter()将会非常简单varrebelspilots。filter(function(pilot){returnpilot。factionRebels;});varempirepilots。filter(function(pilot){returnpilot。factionEmpire;});
我们还可以用箭头函数更优雅的表达:constrebelspilots。filter(pilotpilot。factionRebels);constempirepilots。filter(pilotpilot。factionEmpire);
总结:如果callback函数返回true,这个元素将会出现在返回的数组中,如果返回false就不会出现在返回数组中。reduce()
一个简单的例子,你就能感受到。reduce()的用法了。假如你有一个包含一些飞行员以及他们飞行经验的数组。varpilots〔{id:10,name:PoeDameron,years:14,},{id:2,name:TemminSnapWexley,years:30,},{id:41,name:TallissanLintra,years:16,},{id:99,name:ElloAsty,years:22,}〕;
如果你需要知道所有飞行员的总飞行年数。用。reduce()将会非常直观。vartotalYearspilots。reduce(function(accumulator,pilot){returnaccumulatorpilot。years;},0);reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
可以看到我们开始先用0初始化了我们的accumulator的值,如果需要我们可以用其他的值去初始化accumulator。在对每个元素运行callback函数之后,reduce将会返回最终值给我们(例子中:82)
同样我们可以用箭头函数精简我们的代码:consttotalYearspilots。reduce((acc,pilot)accpilot。years,0);
假如我们需要知道飞行员中飞行年限最长的那位,我们可以这样获取:varmostExpPilotpilots。reduce(function(oldest,pilot){return(oldest。years0)pilot。years?oldest:pilot;},{});
总结:reduce可以直观的返回数组里面指定的一个值或者对象。map()。filter()。reduce()结合使用
因为。map()和。filter()都返回一个数组,所以我们可以轻松的用链式编程的方法来综合使用它们。
假设我们有如下数据:varpersonnel〔{id:5,name:LukeSkywalker,pilotingScore:98,shootingScore:56,isForceUser:true,},{id:82,name:SabineWren,pilotingScore:73,shootingScore:99,isForceUser:false,},{id:22,name:ZebOrellios,pilotingScore:20,shootingScore:59,isForceUser:false,},{id:15,name:EzraBridger,pilotingScore:43,shootingScore:67,isForceUser:true,},{id:11,name:CalebDume,pilotingScore:71,shootingScore:85,isForceUser:true,},〕;
我们的目标是:获取属性为force的用户总值,读者可以先自行思考一下,用于巩固前面所学知识,我们可以如下处理。vartotalJediScorepersonnel。filter(function(person){returnperson。isForceUser;})。map(function(jedi){returnjedi。pilotingScorejedi。shootingScore;})。reduce(function(acc,score){returnaccscore;},0);
同样,我们也可以用箭头表达式精简他们。consttotalJediScorepersonnel。filter(personperson。isForceUser)。map(jedijedi。pilotingScorejedi。shootingScore)。reduce((acc,score)accscore,0);