使用JavaScript检测函数参数名称

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。 我很快意识到,他们正在读取函数签名以查找常见的回调参数名称,例如callbackcb 。 该策略似乎很奇怪,但可能是必要的。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值