Home > Article > Web Front-end > JavaScript method to get all parameter names of function_javascript tips
I wrote a JavaScript function to parse the parameter names of the function, the code is as follows:
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; }); }
The above is the detection function, the sample code is as follows:
function myCustomFn(arg1, arg2,arg3) { // ... } // ["arg1", "arg2", "arg3"] console.log(getArgs(myCustomFn));
Is regular expression a good thing? I don’t know anything else, but it is still very powerful when used in appropriate scenarios!
comes with a Java method to get the current function name: Java gets the function name of the current function in the function
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(); } }
【Run results】
getXXX
getYYY
【Attention】
In line 5 of the code, stacktrace[0].getMethodName() is getStackTrace, stacktrace[1].getMethodName() is getMethodName, and stacktrace[2].getMethodName() is the function name of the function that calls getMethodName.
// Note: the position inside stacktrace;
// [1] is "getMethodName", [2] is the method that calls this method
public static String getMethodName() { StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stacktrace[2]; String methodName = e.getMethodName(); return methodName; }
The above content is the method of getting all parameter names of function in js introduced in this article. Please forgive me if this article is not well written. Welcome to give your valuable opinions.