Underscoreprovidesover100functionsthatsupportbothyourfavoriteworkadayfunctionalhelpers:map,filter,invoke—aswellasmorespecializedgoodies:functionbinding,javascripttemplating,creatingquickindexes,deepequalitytesting,andsoon.
Ifyouarehardcodingthepathtothefilewithinthepackageandyouareunsurewhichbuildtouse,itisverylikelythatyouneedunderscore-umd.jsortheminifiedvariantunderscore-umd-min.js.
Forfunctionswithmultiplealiases,thefilenameofthemoduleisalwaysthefirstnamethatappearsinthedocumentation.Forexample,_.reduce/_.inject/_.foldlisexportedfromunderscore/modules/reduce.js.ModularusageismostlyrecommendedforcreatingacustomizedbuildofUnderscore.
Underscore1.xisbackwardscompatiblewithanyenginethatfullysupportsES3,whilealsoutilizingnewerfeatureswhenavailable,suchasObject.keys,typedarraysandESmodules.WeroutinelyrunourunittestsagainsttheJavaScriptengineslistedbelow:
Inaddition:
Underscore2.xwilllikelyremovesupportforsomeoutdatedenvironments.
_.each([1,2,3],alert);=>alertseachnumberinturn..._.each({one:1,two:2,three:3},alert);=>alertseachnumbervalueinturn...Note:Collectionfunctionsworkonarrays,objects,andarray-likeobjectssuchasarguments,NodeListandsimilar.Butitworksbyduck-typing,soavoidpassingobjectswithanumericlengthproperty.It'salsogoodtonotethataneachloopcannotbebrokenoutof—tobreak,use_.findinstead.
Ifnomemoispassedtotheinitialinvocationofreduce,theiterateeisnotinvokedonthefirstelementofthelist.Thefirstelementisinsteadpassedasthememointheinvocationoftheiterateeonthenextelementinthelist.
Ifnomatchisfound,oriflistisempty,undefinedwillbereturned.
_.compact([0,1,false,2,'',3]);=>[1,2,3]ArrayFunctionsNote:Allarrayfunctionswillalsoworkontheargumentsobject.However,Underscorefunctionsarenotdesignedtoworkon"sparse"arrays.
Bydefault,throttlewillexecutethefunctionassoonasyoucallitforthefirsttime,and,ifyoucallitagainanynumberoftimesduringthewaitperiod,assoonasthatperiodisover.Ifyou'dliketodisabletheleading-edgecall,pass{leading:false},andifyou'dliketodisabletheexecutiononthetrailing-edge,pass{trailing:false}.
varthrottled=_.throttle(updatePosition,100);$(window).scroll(throttled);Ifyouneedtocancelascheduledthrottle,youcancall.cancel()onthethrottledfunction.
Attheendofthewaitinterval,thefunctionwillbecalledwiththeargumentsthatwerepassedmostrecentlytothedebouncedfunction.
Passtruefortheimmediateargumenttocausedebouncetotriggerthefunctionontheleadinginsteadofthetrailingedgeofthewaitinterval.Usefulincircumstanceslikepreventingaccidentaldouble-clicksona"submit"buttonfromfiringasecondtime.
varlazyLayout=_.debounce(calculateLayout,300);$(window).resize(lazyLayout);Ifyouneedtocancelascheduleddebounce,youcancall.cancel()onthedebouncedfunction.
varunderscore=_.noConflict();The_.noConflictfunctionisnotpresentifyouusetheEcmaScript6,AMDorCommonJSmodulesystemtoimportUnderscore.
//Novalue_.iteratee();=>_.identity()//Function_.iteratee(function(n){returnn*2;});=>function(n){returnn*2;}//Object_.iteratee({firstName:'Chelsea'});=>_.matcher({firstName:'Chelsea'});//Anythingelse_.iteratee('firstName');=>_.property('firstName');ThefollowingUnderscoremethodstransformtheirpredicatesthrough_.iteratee:countBy,every,filter,find,findIndex,findKey,findLastIndex,groupBy,indexBy,map,mapObject,max,min,partition,reject,some,sortBy,sortedIndex,anduniq
Youmayoverwrite_.iterateewithyourowncustomfunction,ifyouwantadditionalordifferentshorthandsyntaxes:
varcompiled=_.template("hello:<%=name%>");compiled({name:'moe'});=>"hello:moe"vartemplate=_.template("<%-value%>");template({value:'