首页 > 八卦生活->each的用法(EachvsforEachAComprehensiveGuide)

each的用法(EachvsforEachAComprehensiveGuide)

草原的蚂蚁+ 论文 837 次浏览 评论已关闭

Eachvs.forEach:AComprehensiveGuide

WhenworkingwitharraysinJavaScript,youwilloftencomeacrosstheneedtoiterateovertheelementsofthearrayandperformsomeoperationoneachelement.Therearetwomethodsthatallowyoutodothis:forEachandeach.Whiletheymayseemsimilaratfirst,theyareactuallyquitedifferent.Inthisarticle,wewillexplorethedifferencesbetweenthetwomethodsandwhenyoushoulduseeachone.

TheBasicDifferences

ThefirstthingtounderstandisthateachisnotanativeJavaScriptmethod.ItisactuallyamethodprovidedbythejQuerylibrary.Ontheotherhand,forEachisamethodthatisbuiltintothelanguageitselfandisavailableonallarrays.

Oneimportantdifferencebetweenthetwomethodsishowtheyhandlethereturnvalue.forEachalwaysreturnsundefined,whichmeansthatyoucannotuseittocreateanewarrayormodifytheexistingone.each,ontheotherhand,canbeusedtomodifythearraybyreturninganewvalueoneachiteration.

each的用法(Eachvs.forEachAComprehensiveGuide)

UsingforEach

forEachisamethodthattakesacallbackfunctionandexecutesitonceforeachelementinthearray.Thecallbackfunctioncantakeuptothreearguments:thecurrentelementbeingprocessed,theindexofthatelementinthearray,andthearrayitself.

HereisanexampleofusingforEachtoiterateoveranarrayofnumbersandlogeachonetotheconsole:

each的用法(Eachvs.forEachAComprehensiveGuide)

```constnumbers=[1,2,3,4,5];numbers.forEach((number)=>{console.log(number);});```

Asyoucansee,thecallbackfunctionispassedasanargumenttoforEach.Weuseanarrowfunctionhere,butyoucanalsousearegularfunction:

```numbers.forEach(function(number){console.log(number);});```

Usingeach

eachisamethodprovidedbythejQuerylibrary.ItworksinasimilarwaytoforEach,butitcanbeusedtoiterateovernotonlyarrays,butalsoobjectsandotheriterabledatatypes.

each的用法(Eachvs.forEachAComprehensiveGuide)

Hereisanexampleofusingeachtoiterateoveranarrayofnumbersandmodifyeachone:

```constnumbers=[1,2,3,4,5];$.each(numbers,(index,number)=>{numbers[index]=number*2;});```

Inthisexample,wepassthearrayandacallbackfunctiontoeach.Thecallbackfunctiontakestwoarguments:theindexofthecurrentelementandthevalueofthatelement.Wethenmodifythearraybymultiplyingeachelementby2andassigningitbacktothesameindex.

WhichOneShouldYouUse?

Sowhichmethodshouldyouuse?Aswithmanythingsinprogramming,theansweris\"itdepends\".Herearesomegeneralguidelines:

  • UseforEachwhenyouneedtoperformasimpleoperationoneachelementofanarrayandyoudon'tneedtomodifythearray.
  • Useeachwhenyouneedtomodifythearrayorifyouneedtoiterateoversomethingotherthananarray.
  • IfyouareusingjQueryinyourproject,considerusingeachforconsistency.

Intheend,thechoicebetweenforEachandeachcomesdowntopersonalpreferenceandthespecificrequirementsofyourproject.