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

后端 未结 8 1760
孤城傲影
孤城傲影 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:06

    args = f => f.toString ()
        .replace( /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,'')
        .replace(/(\r\n\t|\n|\r\t)/gm,"")
        .trim()
        .match (/(?:\w*?\s?function\*?\s?\*?\s*\w*)?\s*(?:\((.*?)\)|([^\s]+))/)
        .slice (1,3)
        .join ('').replace(/\s/g, '').
        split (/\s*,\s*/);
    
    /*Test*/
    console.log(args((a,b)=>a+b));
    console.log(args(function(c,d){return c+d;}));
    console.log(args(async function(a,b,c){/**/}));
    console.log(args(function* (a,b,c,d){/**/}));
    console.log(args(function name(s1,s2){}));
    console.log(args(function name(/*comment 1*/ s3/*comment2*/,s4//
    ){}));
    console.log(args(async function* name(/*comment1*/ s5/*comment2*/,s6){}));
    
    console.log(args(async function * name(/*comment1*/ s7/*comment2*/,s8){}));
    
    console.log(args(async function *name(/*comment1*/ s9/*comment2*/,s10){}));

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题