我写了一个 JavaScript函数来解析函数的参数名称,代码如下:
rush:js;">
function getArgs(func) {
// 先用正则匹配,取得符合参数模式的字符串.
// 第一个分组是这个: ([^)]*) 非右括号的任意字符
var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
// 用逗号来分隔参数(arguments string).
return args.split(",").map(function(arg) {
// 去除注释(inline comments)以及空格
return arg.replace(/\/\*.*\*\//,"").trim();
}).filter(function(arg) {
// 确保没有 undefined.
return arg;
});
}
rush:js;">
function myCustomFn(arg1,arg2,arg3) {
// ...
}
// ["arg1","arg2","arg3"]
console.log(getArgs(myCustomFn));
正则表达式(regular expression) 是个好东西吗? 别的我不知道,但在适当的场景用起来还是很给力的!
附带一个Java取得当前函数名的方法: Java 在函数中获取当前函数的函数名
rush: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
rush:java;">
public static String getmethodName() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];
String methodName = e.getmethodName();
return methodName;
}
以上内容是本文给大家介绍的js获取function所有参数名的方法,本文写的不好还请大家见谅,欢迎大家提出宝贵意见。
原文地址:https://www.jb51.cc/js/51929.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。