In JavaScript, you can use the length attribute of the arguments object to get the number of parameters of a method (function). This attribute can get the number of actual parameters of the function; use the length attribute of the function object to get the shape of the function. Number of parameters.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method (method) is a JavaScript function called through an object. In other words, methods are also functions, just special functions.
In JavaScript, you can use the length property of the arguments object to get the number of actual parameters of the function. The arguments object is only visible within the function body, so arguments.length
can only be used within the function body.
Use the length property of the function object to get the number of formal parameters of the function. This attribute is a read-only attribute and can be used inside and outside the function body.
Example
The following example designs a checkArg() function to detect whether the formal parameters and actual parameters of a function are consistent. If they are inconsistent, an exception will be thrown.
function checkArg(a) { //检测函数实参与形参是否一致 if (a.length != a.callee.length) //如果实参与形参个数不同,则抛出错误 throw new Error("实参和形参不一致"); } function f(a, b) { //求两个数的平均值 checkArg(arguments); //根据arguments来检测函数实参和形参是否一致 return ((a * 1 ? a : 0) + (b * 1 ? b : 0)) / 2; //返回平均值 } console.log(f(6)); //抛出异常。调用函数f,传入一个参数
Explanation:
arguments object represents the actual parameter collection of the function, which can only be visible in the function body and can be accessed directly.
The length attribute and callee attribute of the arguments object are the most commonly used:
Use the length attribute to get the number of actual parameters of the function. The arguments object is only visible inside the function body, so arguments.length can only be used inside the function body.
Use the callee attribute to refer to the function where the current arguments object is located. Use the callee attribute to call the function itself within the function body. In anonymous functions, the callee attribute is useful. For example, it can be used to design recursive calls.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to get the number of parameters of a method (function) in javascript. For more information, please follow other related articles on the PHP Chinese website!