each的用法(EachvsforEachAComprehensiveGuide)

Eachvs.forEach:AComprehensiveGuide
WhenworkingwitharraysinJavaScript,youwilloftencomeacrosstheneedtoiterateovertheelementsofthearrayandperformsomeoperationoneachelement.Therearetwomethodsthatallowyoutodothis:forEach
andeach
.Whiletheymayseemsimilaratfirst,theyareactuallyquitedifferent.Inthisarticle,wewillexplorethedifferencesbetweenthetwomethodsandwhenyoushoulduseeachone.
TheBasicDifferences
Thefirstthingtounderstandisthateach
isnotanativeJavaScriptmethod.ItisactuallyamethodprovidedbythejQuerylibrary.Ontheotherhand,forEach
isamethodthatisbuiltintothelanguageitselfandisavailableonallarrays.
Oneimportantdifferencebetweenthetwomethodsishowtheyhandlethereturnvalue.forEach
alwaysreturnsundefined
,whichmeansthatyoucannotuseittocreateanewarrayormodifytheexistingone.each
,ontheotherhand,canbeusedtomodifythearraybyreturninganewvalueoneachiteration.
UsingforEach
forEach
isamethodthattakesacallbackfunctionandexecutesitonceforeachelementinthearray.Thecallbackfunctioncantakeuptothreearguments:thecurrentelementbeingprocessed,theindexofthatelementinthearray,andthearrayitself.
HereisanexampleofusingforEach
toiterateoveranarrayofnumbersandlogeachonetotheconsole:
Asyoucansee,thecallbackfunctionispassedasanargumenttoforEach
.Weuseanarrowfunctionhere,butyoucanalsousearegularfunction:
Usingeach
each
isamethodprovidedbythejQuerylibrary.ItworksinasimilarwaytoforEach
,butitcanbeusedtoiterateovernotonlyarrays,butalsoobjectsandotheriterabledatatypes.
Hereisanexampleofusingeach
toiterateoveranarrayofnumbersandmodifyeachone:
Inthisexample,wepassthearrayandacallbackfunctiontoeach
.Thecallbackfunctiontakestwoarguments:theindexofthecurrentelementandthevalueofthatelement.Wethenmodifythearraybymultiplyingeachelementby2andassigningitbacktothesameindex.
WhichOneShouldYouUse?
Sowhichmethodshouldyouuse?Aswithmanythingsinprogramming,theansweris\"itdepends\".Herearesomegeneralguidelines:
- Use
forEach
whenyouneedtoperformasimpleoperationoneachelementofanarrayandyoudon'tneedtomodifythearray. - Use
each
whenyouneedtomodifythearrayorifyouneedtoiterateoversomethingotherthananarray. - IfyouareusingjQueryinyourproject,considerusing
each
forconsistency.
Intheend,thechoicebetweenforEach
andeach
comesdowntopersonalpreferenceandthespecificrequirementsofyourproject.