Arguments 物件- JavaScript - MDN Web Docs - Mozilla

文章推薦指數: 80 %
投票人數:10人

The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function's arguments within the ... SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件FunctionsArguments物件ArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.語法描述屬性範例規範瀏覽器相容性參見RelatedTopics JavaScript Tutorials: Completebeginners JavaScriptbasics JavaScriptfirststeps JavaScriptbuildingblocks IntroducingJavaScriptobjects JavaScriptGuide Introduction Grammarandtypes Controlflowanderrorhandling Loopsanditeration Functions Expressionsandoperators Numbersanddates Textformatting Regularexpressions Indexedcollections Keyedcollections Workingwithobjects Usingclasses Usingpromises Iteratorsandgenerators Metaprogramming JavaScriptmodules Intermediate Client-sideJavaScriptframeworks Client-sidewebAPIs Are-introductiontoJavaScript JavaScriptdatastructures Equalitycomparisonsandsameness Closures Advanced Inheritanceandtheprototypechain Strictmode JavaScripttypedarrays MemoryManagement ConcurrencymodelandEventLoop References: Built-inobjects AggregateErrorArrayArrayBufferAsyncFunctionAsyncGeneratorAsyncGeneratorFunctionAtomicsBigIntBigInt64ArrayBigUint64ArrayBooleanDataViewDatedecodeURI()decodeURIComponent()encodeURI()encodeURIComponent()Error Deprecated escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8ArrayInternalErrorIntlisFinite()isNaN()JSONMapMathNaNNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined Deprecated unescape()URIErrorWeakMapWeakRefWeakSetWebAssembly Expressions&operators Addition(+)Additionassignment(+=)Assignment(=)asyncfunctionexpressionasyncfunction*expressionawaitBitwiseAND(&)BitwiseANDassignment(&=)BitwiseNOT(~)BitwiseOR(|)BitwiseORassignment(|=)BitwiseXOR(^)BitwiseXORassignment(^=)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivision(/)Divisionassignment(/=)Equality(==)Exponentiation(**)Exponentiationassignment(**=)Functionexpressionfunction*expressionGreaterthan(>)Greaterthanorequal(>=)Groupingoperator()importimport.metainoperatorIncrement(++)Inequality(!=)instanceofLeftshift(<>)Rightshiftassignment(>>=)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtraction(-)Subtractionassignment(-=)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshift(>>>)Unsignedrightshiftassignment(>>>=)voidoperatoryieldyield* Statements&declarations asyncfunctionasyncfunction*blockbreakclassconstcontinuedebuggerdo...whileemptyexportforforawait...offor...infor...offunctiondeclarationfunction*if...elseimportlabelletreturnswitchthrowtry...catchvarwhile Deprecated with Functions TheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter Classes ClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic Errors Warning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionRangeError:BigIntdivisionbyzeroRangeError:BigIntnegativeexponentTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration'X'beforeinitializationTypeError:can'tassigntoproperty"x"on"y":notanobjectRangeError:xcan'tbeconvertedtoBigIntbecauseitisn'tanintegerTypeError:can'tconvertBigInttonumberTypeError:can'tconvertxtoBigIntTypeError:can'tdefineproperty"x":"obj"isnotextensibleTypeError:property"x"isnon-configurableandcan'tbedeletedTypeError:can'tredefinenon-configurableproperty"x"SyntaxError:cannotuse`??`unparenthesizedwithin`||`and`&&`expressionsTypeError:cyclicobjectvalueTypeError:can'taccessdeadobjectSyntaxError:applyingthe'delete'operatortoanunqualifiednameisdeprecatedReferenceError:deprecatedcallerorargumentsusageWarning:expressionclosuresaredeprecatedSyntaxError:"0"-prefixedoctalliteralsandoctalescapeseq.aredeprecatedSyntaxError:Using//@toindicatesourceURLpragmasisdeprecated.Use//#insteadWarning:String.xisdeprecated;useString.prototype.xinsteadWarning:Date.prototype.toLocaleFormatisdeprecatedSyntaxError:testforequality(==)mistypedasassignment(=)?TypeError:settinggetter-onlyproperty"x"SyntaxError:Unexpected'#'usedoutsideofclassbodySyntaxError:identifierstartsimmediatelyafternumericliteralSyntaxError:illegalcharacterTypeError:cannotuse'in'operatortosearchfor'x'in'y'RangeError:invalidarraylengthSyntaxError:invalidassignmentleft-handsideSyntaxError:invalidBigIntsyntaxTypeError:invalidassignmenttoconst"x"RangeError:invaliddateSyntaxError:for-inloopheaddeclarationsmaynothaveinitializersSyntaxError:adeclarationintheheadofafor-ofloopcan'thaveaninitializerTypeError:invalid'instanceof'operand'x'TypeError:'x'isnotiterableSyntaxError:JSON.parse:badparsingSyntaxError:MalformedformalparameterURIError:malformedURIsequenceSyntaxError:missing]afterelementlistSyntaxError:missing:afterpropertyidSyntaxError:missing}afterfunctionbodySyntaxError:missing}afterpropertylistSyntaxError:missingformalparameterSyntaxError:missing=inconstdeclarationSyntaxError:missingnameafter.operatorSyntaxError:missing)afterargumentlistSyntaxError:missing)afterconditionSyntaxError:missing;beforestatementTypeError:MoreargumentsneededRangeError:repeatcountmustbenon-negativeTypeError:"x"isnotanon-nullobjectTypeError:"x"hasnopropertiesSyntaxError:missingvariablenameTypeError:can'tdeletenon-configurablearrayelementRangeError:argumentisnotavalidcodepointTypeError:"x"isnotaconstructorTypeError:"x"isnotafunctionReferenceError:"x"isnotdefinedRangeError:precisionisoutofrangeError:Permissiondeniedtoaccessproperty"x"TypeError:"x"isread-onlySyntaxError:redeclarationofformalparameter"x"TypeError:ReduceofemptyarraywithnoinitialvalueSyntaxError:"x"isareservedidentifierRangeError:repeatcountmustbelessthaninfinityWarning:unreachablecodeafterreturnstatementSyntaxError:"usestrict"notallowedinfunctionwithnon-simpleparametersInternalError:toomuchrecursionReferenceError:assignmenttoundeclaredvariable"x"ReferenceError:referencetoundefinedproperty"x"SyntaxError:UnexpectedtokenTypeError:"x"is(not)"y"SyntaxError:functionstatementrequiresanameSyntaxError:unparenthesizedunaryexpressioncan'tappearontheleft-handsideof'**'SyntaxError:unterminatedstringliteral Misc JavaScripttechnologiesoverview Lexicalgrammar JavaScriptdatastructures Enumerabilityandownershipofproperties Iterationprotocols Strictmode Transitioningtostrictmode Templateliterals Deprecatedfeatures 語法描述屬性範例規範瀏覽器相容性參見Arguments物件arguments物件是一個對應傳入函式之引數的類陣列(Array-like)物件。

語法arguments 描述 備註:如果你有在使用ES6語法,建議參考其餘參數。

備註:「類陣列(Array-like)」的意思是arguments一樣擁有length這項屬性,以及從0開始的索引,但是它沒有陣列內建的方法像是forEach(),或是map()。

Theargumentsobjectisalocalvariableavailablewithinall(non-arrow)functions.Youcanrefertoafunction'sargumentswithinthefunctionbyusingtheargumentsobject.Thisobjectcontainsanentryforeachargumentpassedtothefunction,thefirstentry'sindexstartingat0. Forexample,ifafunctionispassedthreearguments,youcanrefertothemasfollows: arguments[0] arguments[1] arguments[2] arguments也可以被指定: arguments[1]='newvalue'; arguments物件不是陣列。

它與陣列非常相似,但是它沒有除了length這個屬性以外的其他陣列屬性。

舉例,它沒有pop這個陣列方法。

然而,它依然可以被轉換為真正的陣列(Array)。

varargs=Array.prototype.slice.call(arguments); varargs=[].slice.call(arguments); //ES2015 constargs=Array.from(arguments); 警告:UsingsliceonargumentspreventsoptimizationsinsomeJavaScriptengines(V8forexample-moreinformation).Ifyoucareforthem,tryconstructinganewarraybyiteratingthroughtheargumentsobjectinstead.AnalternativewouldbetousethedespisedArrayconstructorasafunction: varargs=(arguments.length===1?[arguments[0]]:Array.apply(null,arguments)); Youcanusetheargumentsobjectifyoucallafunctionwithmoreargumentsthanitisformallydeclaredtoaccept.Thistechniqueisusefulforfunctionsthatcanbepassedavariablenumberofarguments.Usearguments.lengthtodeterminethenumberofargumentspassedtothefunction,andthenprocesseachargumentbyusingtheargumentsobject.Todeterminethenumberofparametersinthefunctionsignature,usetheFunction.lengthproperty.UsingtypeofwithArgumentsThetypeofargumentsreturns'object'. console.log(typeofarguments);//'object' Thetypeofindividualargumentscanbedeterminedwiththeuseofindexing. console.log(typeofarguments[0]);//thiswillreturnthetypeofindividualarguments. UsingtheSpreadSyntaxwithArgumentsYoucanalsousetheArray.from()methodorthespreadoperatortoconvertargumentstoarealArray: varargs=Array.from(arguments); varargs=[...arguments]; 屬性 arguments.callee Referencetothecurrentlyexecutingfunction. arguments.caller Deprecated Referencetothefunctionthatinvokedthecurrentlyexecutingfunction. arguments.length Referencetothenumberofargumentspassedtothefunction. arguments[@@iterator] ReturnsanewArrayIteratorobjectthatcontainsthevaluesforeachindexinthearguments. 範例DefiningafunctionthatconcatenatesseveralstringsThisexampledefinesafunctionthatconcatenatesseveralstrings.Theonlyformalargumentforthefunctionisastringthatspecifiesthecharactersthatseparatetheitemstoconcatenate.Thefunctionisdefinedasfollows: functionmyConcat(separator){ varargs=Array.prototype.slice.call(arguments,1); returnargs.join(separator); } Youcanpassanynumberofargumentstothisfunction,anditcreatesalistusingeachargumentasaniteminthelist. //returns"red,orange,blue" myConcat(',','red','orange','blue'); //returns"elephant;giraffe;lion;cheetah" myConcat(';','elephant','giraffe','lion','cheetah'); //returns"sage.basil.oregano.pepper.parsley" myConcat('.','sage','basil','oregano','pepper','parsley'); DefiningafunctionthatcreatesHTMLlistsThisexampledefinesafunctionthatcreatesastringcontainingHTMLforalist.Theonlyformalargumentforthefunctionisastringthatis"u"ifthelististobeunordered(bulleted),or"o"ifthelististobeordered(numbered).Thefunctionisdefinedasfollows: functionlist(type){ varresult='

  • '; varargs=Array.prototype.slice.call(arguments,1); result+=args.join('
  • '); result+='
  • '+type+'l>';//endlist returnresult; } Youcanpassanynumberofargumentstothisfunction,anditaddseachargumentasanitemtoalistofthetypeindicated.Forexample: varlistHTML=list('u','One','Two','Three'); /*listHTMLis: "
    • One
    • Two
    • Three
    " */ Rest,default,anddestructuredparametersTheargumentsobjectcanbeusedinconjunctionwithrest,default,anddestructuredparameters. functionfoo(...args){ returnargs; } foo(1,2,3);//[1,2,3] Whilethepresenceofrest,default,ordestructuredparametersdoesnotalterthebehavioroftheargumentsobjectinstrictmodecode,thereisasubtledifferencefornon-strictcode. Whenanon-strictfunctiondoesnotcontainrest,default,ordestructuredparameters,thenthevaluesintheargumentsobjectdotrackthevaluesofthearguments(andviceversa).Seethecodebelow: functionfunc(a){ arguments[0]=99;//updatingarguments[0]alsoupdatesa console.log(a); } func(10);//99 and functionfunc(a){ a=99;//updatingaalsoupdatesarguments[0] console.log(arguments[0]); } func(10);//99 Whenanon-strictfunctiondoescontainrest,default,ordestructuredparameters,thenthevaluesintheargumentsobjectdonottrackthevaluesofthearguments(andviceversa).Instead,theyreflecttheargumentsprovidedatthetimeofinvocation: functionfunc(a=55){ arguments[0]=99;//updatingarguments[0]doesnotalsoupdatea console.log(a); } func(10);//10 and functionfunc(a=55){ a=99;//updatingadoesnotalsoupdatearguments[0] console.log(arguments[0]); } func(10);//10 and functionfunc(a=55){ console.log(arguments[0]); } func();//undefined 規範SpecificationECMAScriptLanguageSpecification#sec-arguments-exotic-objects瀏覽器相容性BCDtablesonlyloadinthebrowser參見 Function Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:2022年8月20日,byMDNcontributors


    請為這篇文章評分?