Get function parameter names for interface purposes

前端 未结 5 1253
灰色年华
灰色年华 2021-01-01 03:36

can anyone help me on how to retrieve function parameter names? For example:

var A = function(a, b, c) {};

I need to get the parameter name

相关标签:
5条回答
  • 2021-01-01 03:55

    Now it's 2018 so may I add a solution that supports arrow function

    /**
     *  (Function) => String[]
     */
    function getFnParamNames(fn){
        const fnStr = fn.toString()
        const arrowMatch = fnStr.match(/\(?[^]*?\)?\s*=>/) 
        if (arrowMatch) return arrowMatch[0].replace(/[()\s]/gi,'').replace('=>','').split(',')
        const match = fnStr.match(/\([^]*?\)/) 
        return match ? match[0].replace(/[()\s]/gi,'').split(',') : []
    }
    

    Note:

    [^] matches all kinds of characters including new line (while . excludes new line). Source RegExp Documentation

    *? non-greedy quantifier. More explanation here

    Tested cases:

    console.log(getFnParamNames(name => {
    }))
    
    console.log(getFnParamNames(name=>{
    }))
    
    console.log(getFnParamNames((name) => {
    }))
    
    console.log(getFnParamNames((name, age, ...args) => {
    }))
    
    console.log(getFnParamNames((name,age,...args)=>{
    }))
    
    console.log(getFnParamNames(function(name,age,...args){
    }))
    
    console.log(getFnParamNames(function (name , age , ...args ) {
    }))
    
    console.log(getFnParamNames(function(
        name,
        age,
        ...args){
    }))
    
    console.log(getFnParamNames(new Function('name', 'age' , '...args', 'console.log(args.length)' )))
    
    0 讨论(0)
  • 2021-01-01 04:07

    Just to make complete @jerjer answer, We may also ensure there is at least one match:

    function getFnParamNames(fn){
      const match = fn.toString().match(/\(.*?\)/) 
      return match ? match[0].replace(/[()]/gi,'').replace(/\s/gi,'').split(',') : [];
    }
    
    0 讨论(0)
  • 2021-01-01 04:09

    You can use either a regex such as described in here, another alternative would be to use a tokenizer. The following code uses the acorn javascript parser for checking if a function contains a specific argument name:

    function isFunction(value) {
      return value && typeof value === 'function';
    }
    
    function hasArgument(func, name) {
    
    if (!isFunction(func) || !name) {
        return false;
    }
    
    var tokenizer = acorn.tokenize(func);
    var token = tokenizer();
    
    while (token.type.type !== 'eof') {
    
        // ')' closes function, we do not want to look inside the function body
        if (token.type.type === ')') {
            return false;
        }
    
        if (token.type.type === 'name' && token.value === name) {
            return true;
        }
    
        token = tokenizer();
    
    }
    
    return false;
    

    }

    0 讨论(0)
  • 2021-01-01 04:13

    I doubt that there is any decent way to this, in javascript parameter values can be of different type when passed, the types doesn't matter but the order thus.

    This might not be the answer that you are looking for but this could help at least.

    function test(a,b,c,d) {
    
    }
    
    //this will give us the number of parameters defined in the a function.
    confirm(test.length); 
    

    To really know the names you can parse the function definition

      var str = window['test'].toString();
       //str will be "function test(a,b,c,d){}"
    

    Below is a simple parsing test I made:

    function test(a,b,c,d)
    {
    
    }
    
    var b = function(x,y,  z){};
    alert(getFnParamNames(b).join(","));
    alert(getFnParamNames(test).join(","));
    
    function getFnParamNames(fn){
        var fstr = fn.toString();
        return fstr.match(/\(.*?\)/)[0].replace(/[()]/gi,'').replace(/\s/gi,'').split(',');
    }
    
    0 讨论(0)
  • 2021-01-01 04:15

    The only way would be to retrieve the function as a string and use a RegExp to get the parameter names:

    function test(a,b,c){/*function body*/}
    //=> this should return 'a,b,c':
    test.toString().replace(/(function.+\()(.+(?=\)))(.+$)/,'$2');
    
    0 讨论(0)
提交回复
热议问题