In some scenarios, accessing the parameter names and values of a function dynamically becomes necessary. This article explores a robust solution to this problem.
The following function, getParamNames, can extract the parameter names of any provided function:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var ARGUMENT_NAMES = /([^\s,]+)/g; function getParamNames(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; }
getParamNames(getParamNames) // returns ['func'] getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d'] getParamNames(function (a,/*b,c,*/d){}) // returns ['a','d'] getParamNames(function (){}) // returns []
With the advent of ES6, default parameters can trip up the getParamNames function. To address this, an updated version is provided:
var STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\'|[^'\r\n])*')|("(?:\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;
While this enhanced version handles default parameters in most cases, exceptions may occur.
In addition to obtaining parameter names, one may also require the corresponding values. This is readily accessible through the arguments local variable, which can be converted to an array:
var args = Array.prototype.slice.call(arguments);
Alternatively, if array generics are available:
var args = Array.slice(arguments);
By employing these techniques, developers can dynamically access the parameters and values of functions for various needs and customizations.
The above is the detailed content of How Can I Dynamically Retrieve JavaScript Function Parameter Names and Values?. For more information, please follow other related articles on the PHP Chinese website!