JavaScript获取function所有参数名的方法

(编辑:jimmy 日期: 2024/10/5 浏览:2)

我写了一个 JavaScript函数来解析函数的参数名称, 代码如下:

function getArgs(func) {
 // 先用正则匹配,取得符合参数模式的字符串.
 // 第一个分组是这个: ([^)]*) 非右括号的任意字符
 var args = func.toString().match(/function\s.*",").map(function(arg) {
  // 去除注释(inline comments)以及空格
  return arg.replace(/\/\*.*\*\//, "").trim();
 }).filter(function(arg) {
  // 确保没有 undefined.
  return arg;
 });
}

上面是检测的函数, 示例代码如下:

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

正则表达式(regular expression) 是个好东西吗"color: #ff0000">附带一个Java取得当前函数名的方法: Java 在函数中获取当前函数的函数名

public class Test { 
  private String getMethodName() { 
    StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 
    StackTraceElement e = stacktrace[2]; 
    String methodName = e.getMethodName(); 
    return methodName; 
  } 
  public void getXXX() { 
    String methodName = getMethodName(); 
    System.out.println(methodName); 
  } 
  public void getYYY() { 
    String methodName = getMethodName(); 
    System.out.println(methodName); 
  } 
  public static void main(String[] args) { 
    Test test = new Test(); 
    test.getXXX(); 
    test.getYYY(); 
  } 
}

【运行结果】

getXXX 
getYYY 

【注意】

代码第5行,stacktrace[0].getMethodName() 是 getStackTrace,stacktrace[1].getMethodName() 是 getMethodName,stacktrace[2].getMethodName() 才是调用 getMethodName 的函数的函数名。

// 注意: stacktrace里面的位置;
// [1] 是“getMethodName”, [2] 是调用此方法的method

public static String getMethodName() { 
  StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 
  StackTraceElement e = stacktrace[2]; 
  String methodName = e.getMethodName(); 
  return methodName; 
}

以上内容是本文给大家介绍的js获取function所有参数名的方法,本文写的不好还请大家见谅,欢迎大家提出宝贵意见。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。