使用JavaScript检测函数参数名称

    技术2022-07-11  173

    I was recently looking over the promisify-node code to see how the author was able to convert basic functions and objects to a promised-based API.  I quickly realized that they were reading function signatures to look for common callback argument names like callback and cb.  The strategy seemed odd but probably necessary.

    我最近正在查看promisify节点代码,以了解作者如何将基本功能和对象转换为基于承诺的API。 我很快意识到,他们正在读取函数签名以查找常见的回调参数名称,例如callback和cb 。 该策略似乎很奇怪,但可能是必要的。

    I took a few minutes to pick out the JavaScript function which parsed argument names for a function and here it is:

    我花了几分钟时间挑选出JavaScript函数,该函数解析了函数的参数名称,如下所示:

    function getArgs(func) { // First match everything inside the function argument parens. var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1]; // Split the arguments string into an array comma delimited. return args.split(',').map(function(arg) { // Ensure no inline comments are parsed and trim the whitespace. return arg.replace(/\/\*.*\*\//, '').trim(); }).filter(function(arg) { // Ensure no undefined values are added. return arg; }); }

    So given the function above and a sample function, here's how it would work:

    因此,鉴于上述功能和示例功能,这是它的工作方式:

    function myCustomFn(arg1, arg2,arg3) { } console.log(getArgs(myCustomFn)); // ["arg1", "arg2", "arg3"]

    Aren't regular expressions a beautiful thing?  I can't name many uses for such a function but here it is if you're looking to do such a thing!

    正则表达式不是美丽的东西吗? 我不能说这种功能有很多用途,但是如果您正在寻找做这样的事情,那就在这里!

    翻译自: https://davidwalsh.name/javascript-arguments

    Processed: 0.016, SQL: 9