Home  >  Article  >  Web Front-end  >  How to get function parameter names using JS

How to get function parameter names using JS

php中世界最好的语言
php中世界最好的语言Original
2018-06-04 11:35:582998browse

This time I will show you how to use JS to get the function parameter name, what are the precautions for using JS to get the function parameter name, the following is a practical case, let’s take a look .

When I was browsing webhak.com, I saw a method that can get the function parameter name through javaScript. I thought it used regular expressions very cleverly. I read it and wrote it down first. Maybe it will be useful in the future. .

function getArgs(func){
		//匹配函数括号里的参数
		var args=func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
		//分解参数成数组
		return args.split(",").map(function (arg){
			//去空格和内联注释
			return arg.replace(/\/\*.*\*\//,"").trim();
		}).filter(function(args) {
			//确保没有undefineds
			return args;
		});
	}


With this method, we can write a test function to test it.

function test(agr1,arg2,arg3){
		//这里是注释
		/*这里也是注释*/
	}
	console.log(getArgs(test));

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use Web Storage storage

How to use H5 to upload images

The above is the detailed content of How to get function parameter names using JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn