How to get function parameter names/values dynamically?

前端 未结 30 2649
说谎
说谎 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 00:41

    You can also use "esprima" parser to avoid many issues with comments, whitespace and other things inside parameters list.

    function getParameters(yourFunction) {
        var i,
            // safetyValve is necessary, because sole "function () {...}"
            // is not a valid syntax
            parsed = esprima.parse("safetyValve = " + yourFunction.toString()),
            params = parsed.body[0].expression.right.params,
            ret = [];
    
        for (i = 0; i < params.length; i += 1) {
            // Handle default params. Exe: function defaults(a = 0,b = 2,c = 3){}
            if (params[i].type == 'AssignmentPattern') {
                ret.push(params[i].left.name)
            } else {
                ret.push(params[i].name);
            }
        }
    
        return ret;
    }
    

    It works even with code like this:

    getParameters(function (hello /*, foo ),* /bar* { */,world) {}); // ["hello", "world"]
    

提交回复
热议问题