How to get function parameter names/values dynamically?

前端 未结 30 2616
说谎
说谎 2020-11-22 00:13

Is there a way to get the function parameter names of a function dynamically?

Let’s say my function looks like this:

function doSomething(param1, par         


        
30条回答
  •  遇见更好的自我
    2020-11-22 00:31

    Taking the answer from @jack-allan I modified the function slightly to allow ES6 default properties such as:

    function( a, b = 1, c ){};
    

    to still return [ 'a', 'b' ]

    /**
     * Get the keys of the paramaters of a function.
     *
     * @param {function} method  Function to get parameter keys for
     * @return {array}
     */
    var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
    var ARGUMENT_NAMES = /(?:^|,)\s*([^\s,=]+)/g;
    function getFunctionParameters ( func ) {
        var fnStr = func.toString().replace(STRIP_COMMENTS, '');
        var argsList = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')'));
        var result = argsList.match( ARGUMENT_NAMES );
    
        if(result === null) {
            return [];
        }
        else {
            var stripped = [];
            for ( var i = 0; i < result.length; i++  ) {
                stripped.push( result[i].replace(/[\s,]/g, '') );
            }
            return stripped;
        }
    }
    

提交回复
热议问题