Get function parameter names for interface purposes

前端 未结 5 1281
灰色年华
灰色年华 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条回答
  •  梦毁少年i
    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(',');
    }
    

提交回复
热议问题