Arguments 物件- JavaScript - MDN Web Docs - Mozilla
文章推薦指數: 80 %
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='
- One
- Two
- Three
延伸文章資訊
- 1引數(Argument) vs. 參數(Parameter) - NotFalse 技術客
An argument is an expression used when calling the method. A parameter is the variable which is p...
- 2Python Function Arguments - W3Schools
The terms parameter and argument can be used for the same thing: information that are passed into...
- 3Arguments 物件- JavaScript - MDN Web Docs - Mozilla
The arguments object is a local variable available within all (non-arrow) functions. You can refe...
- 4JavaScript Function Parameters - W3Schools
Function parameters are the names listed in the function definition. Function arguments are the r...
- 5argument of function - 函數的自變數 - 國家教育研究院雙語詞彙
函數的自變數 · argument of function · 名詞解釋: 對應自變數x,y,…的值,若能表為函數f(x,y,…)則上述變數,可以稱為函數的自變數。 · 函數的自變數 · arg...