JavaScript获取function所有参数名的方法
我写了一个JavaScript函数来解析函数的参数名称,代码如下:
functiongetArgs(func){
//先用正则匹配,取得符合参数模式的字符串.
//第一个分组是这个:([^)]*)非右括号的任意字符
varargs=func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
//用逗号来分隔参数(argumentsstring).
returnargs.split(",").map(function(arg){
//去除注释(inlinecomments)以及空格
returnarg.replace(/\/\*.*\*\//,"").trim();
}).filter(function(arg){
//确保没有undefined.
returnarg;
});
}
上面是检测的函数,示例代码如下:
functionmyCustomFn(arg1,arg2,arg3){
//...
}
//["arg1","arg2","arg3"]
console.log(getArgs(myCustomFn));
正则表达式(regularexpression)是个好东西吗?别的我不知道,但在适当的场景用起来还是很给力的!
附带一个Java取得当前函数名的方法:Java在函数中获取当前函数的函数名
publicclassTest{
privateStringgetMethodName(){
StackTraceElement[]stacktrace=Thread.currentThread().getStackTrace();
StackTraceElemente=stacktrace[2];
StringmethodName=e.getMethodName();
returnmethodName;
}
publicvoidgetXXX(){
StringmethodName=getMethodName();
System.out.println(methodName);
}
publicvoidgetYYY(){
StringmethodName=getMethodName();
System.out.println(methodName);
}
publicstaticvoidmain(String[]args){
Testtest=newTest();
test.getXXX();
test.getYYY();
}
}
【运行结果】
getXXX
getYYY
【注意】
代码第5行,stacktrace[0].getMethodName()是getStackTrace,stacktrace[1].getMethodName()是getMethodName,stacktrace[2].getMethodName()才是调用getMethodName的函数的函数名。
//注意:stacktrace里面的位置;
//[1]是“getMethodName”,[2]是调用此方法的method
publicstaticStringgetMethodName(){
StackTraceElement[]stacktrace=Thread.currentThread().getStackTrace();
StackTraceElemente=stacktrace[2];
StringmethodName=e.getMethodName();
returnmethodName;
}
以上内容是本文给大家介绍的js获取function所有参数名的方法,本文写的不好还请大家见谅,欢迎大家提出宝贵意见。