Is it possible to reflect the arguments of a Javascript function?

后端 未结 8 1787
孤城傲影
孤城傲影 2020-12-02 23:21

Is it possible to get all of the arguments a Javascript function is written to accept? (I know that all Javascript function arguments are \"optional\")? If

8条回答
  •  不知归路
    2020-12-03 00:09

    This new version handles fat arrow functions as well...

    args = f => f.toString ().replace (/[\r\n\s]+/g, ' ').
                  match (/(?:function\s*\w*)?\s*(?:\((.*?)\)|([^\s]+))/).
                  slice (1,3).
                  join ('').
                  split (/\s*,\s*/);
    
    function ftest (a,
                     b,
                     c) { }
    
    let aftest = (a,
                     b,
                     c) => a + b / c;
    
    console.log ( args (ftest),  // = ["a", "b", "c"] 
                  args (aftest), // = ["a", "b", "c"]
                  args (args)    // = ["f"]
                 );
    

    Here is what I think you are looking for :

     function ftest (a,
                     b,
                     c) { }
     var args = ftest.toString ().
                  replace (/[\r\n\s]+/g, ' ').
                  match (/function\s*\w*\s*\((.*?)\)/)[1].split (/\s*,\s*/);
    

    args will be an array of the names of the arguments of test i.e. ['a', 'b', 'c']

    The value is args will be an array of the parameter names if the ftest is a function. The array will be empty if ftest has not parameters. The value of args will be null if ftest fails the regular expression match, i.e it is not a function.

提交回复
热议问题