向JavaScript函数传递任意数量的参数
Pass an arbitrary number of parameters into a JavaScript function
我的JavaScript代码只是一个Ajax请求,它期望从后端返回XML。后端可以像这样返回execute_callback
作为XML标记之一:
<?xml version="1.0" encoding="windows-1251"?>
<response>
<execute_callback>
<function_name>someFunction</function_name>
</execute_callback>
</response>
只要你知道callback
期望的参数的确切数量,一切都没问题。但是如果后端返回
<?xml version="1.0" encoding="windows-1251"?>
<response>
<execute_callback>
<function_name>someFunction</function_name>
<param>10.2</param>
<param>some_text</param>
</execute_callback>
<execute_callback>
<function_name>otherFunction</function_name>
<param>{ x: 1, y: 2 }</param>
</execute_callback>
</response>
现在如何将参数10.2和'some_text'传递给someFunction
和JSON {x: 1, y: 2}传递给otherFunction
?
我知道一个丑陋的解决方案(使用函数的arguments
),但我正在寻找一个漂亮的。
在我忘记之前:不要为我解析XML -我可以自己做:)我所需要的只是在JavaScript中向函数传递任意数量的参数的技巧。如果你懂Python,我想要:
def somefunc(x, y):
print x, y
args = { 'x' : 1, 'y' : 2 }
somefunc(**args)
你可以把它们全部传递给你的函数:
function someFunction(){
for(i = 0; i < arguments.length; i++)
alert(arguments[i]);
}
Javascript函数有一个参数数组类对象,使用任意数量的参数调用Javascript函数在语法上是正确的。
someFunction(1, 2, 'test', ['test', 'array'], 5, 0);
是对该函数的有效调用。
您可以参考Function.apply。假设回调函数在全局对象中声明(浏览器中的window
)。
var callback_function = window[function_name];
if (callback_function) { // prevent from calling undefined functions
callback_function.apply(window, params); // params is an array holding all parameters
}
不调用函数,而是通过名称将函数作为关联数组中的元素引用:
var funcName = // parse your xml for function name
var params = new Array();
params[0] = 10.2; // from your parsed xml
params[1] = 'some text'; // also from your parsed xml
// functions are attached to some Object o:
o[funcName](params); // equivalent to o.funcName(params);
我在这里写了一个上面的例子:http://jsbin.com/ewuqur/2/edit
2022答案:您现在可以(Firefox=2012, Chrome=2015, Safari=2016)使用rest
参数:
function someFunction(first, ...extra) {
console.log(`You started with "${first}"`);
extra.forEach(arg => console.log(arg));
}
someFunction(1, 2, 3);
正如Paul的回答所指出的,有一个隐式的arguments
对象,但是arguments
有一些限制。值得注意的是,arguments
包含所有参数,并不是一个真正的数组,而rest
参数是一个真正的数组,并有意省略任何先前命名的参数。上面的例子使用Array.prototype.forEach()
,它不能在arguments
上工作。
参见同时介绍的spread
语法,了解点-点-点-变量表示法的其他用途。
- 从node.js向CasperJS传递参数数组
- 如何将数组中的参数作为不同的参数传递给javascript函数
- 如何从参数数组中调用回调
- 将参数作为不带.apply()的数组传递
- 如何使用JavaScript's”;应用“;方法,在数组之前添加一个额外的参数
- nodeJS中通过URL发送的参数数
- Javascript-如何通过以字符串作为参数返回数组
- JavaScript 函数参数传递数组
- 从具有特定参数的数组中检索对象
- 不允许对链接函数的元素参数进行数组操作
- 如何使用angularjs将带有其他参数的数组发送到web api
- 如何根据参数从数组中删除数字
- 基于"字符串"的任意数组元素;种子
- Javascript程序不使用数学.用for循环求任意数的幂
- Javascript-使用传递的参数更新数组
- 将变量赋值为这两个数之间的任意数
- 如果希望使用javascript数组作为哈希键,请使用任意数组元素进行检索
- 如何创建带参数的数组
- 通过传递函数作为参数合并数组
- Javascript Ajax到ASP.. NET控制器类-数组参数的数组