Dynamically Accessing Function Parameter Information
In JavaScript, it is often desirable to access function parameter names and values dynamically during runtime. This article discusses a method to achieve this functionality.
Getting Parameter Names
To obtain an array of parameter names for any given function, the following function can be used:
var getParamNames = function(func) { var fnStr = func.toString().replace(STRIP_COMMENTS, ''); var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); if(result === null) result = []; return result; };
This function replaces comments and matches the parameter names using a regular expression. For example:
getParamNames(getParamNames) // returns ['func'] getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
Getting Parameter Values
In addition to parameter names, the arguments object can be used to access parameter values within the function itself:
var args = Array.slice(arguments);
This creates an array containing the values of all the function's parameters.
Example Usage
Consider the following function that takes an arbitrary number of parameters:
function doSomething() { // Fill an array with parameter names and values var paramNames = getParamNames(doSomething); var paramValues = Array.slice(arguments); }
Inside the function, the getParamNames function is used to obtain the parameter names, and Array.slice(arguments) is used to obtain the parameter values.
Considerations
The above is the detailed content of How Can I Dynamically Access JavaScript Function Parameter Names and Values?. For more information, please follow other related articles on the PHP Chinese website!