[英]Parse (string) Function Call and Parameters in Javascript
Suppose I have two links: 假设我有两个链接:
<a href="#" onclick="myFunction();"></a>
<a href="#" onclick="myFunction(1, 2, 'string');"></a>
My goal is to parse the myFunction
call and get an array of the parameters. 我的目标是解析
myFunction
调用并获取参数数组。 So from the first link I would want to get []
and from the second link I would want to get [1, 2, 'string']
. 因此,从第一个链接我想获取
[]
,从第二个链接中我想要获取[1, 2, 'string']
。
I already know how to get the onclick
attribute into a string (we are using jQuery here), so that doesn't need to be part of the answer. 我已经知道如何将
onclick
属性转换为字符串(我们在这里使用jQuery),因此不必成为答案的一部分。
Basically: 基本上:
var myCall="myFunction(1, 2, 'string')";
parseFunctionString(myCall); //[1, 2, 'string']
Define parseFunctionString
. 定义
parseFunctionString
。 I am imagining this would msot easily be done with some sort of regex. 我想这可以通过某种正则表达式轻松实现。
You can do this literally with the arguments
keyword, within a function. 您可以在函数内使用
arguments
关键字从字面上进行此操作。 For example: 例如:
function foo() {
alert(arguments[0]);
}
foo('bar');
that will alert 'bar'
, since that's the first argument to the function. 这将提醒
'bar'
,因为这是该函数的第一个参数。 You can use the arguments
keyword just like an array, but it won't have built-in methods like arrays do, so it won't have things like .sort()
. 您可以像数组一样使用
arguments
关键字,但它不会像array那样具有内置方法,因此不会具有.sort()
类的东西。 More info can be found on MDN . 可以在MDN上找到更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.