JavaScript 函数中的无限参数 [英] Unlimited arguments in a JavaScript function
问题描述
JavaScript 函数可以接受无限参数吗?像这样:
Can a JavaScript function take unlimited arguments? Something like this:
testArray(1, 2, 3, 4, 5...);
我正在尝试:
var arr = [];
function testArray(A) {
arr.push(A);
}
但这不起作用(输出只是第一个参数).或者唯一的办法是:
But this doesn't work (output is only the first argument). Or the only way is:
function testArray(a, b, c, d, e...) {
}
谢谢
推荐答案
有一个奇怪的魔法"变量可以引用,称为参数":
There's a weird "magic" variable you can reference called "arguments":
function manyArgs() {
for (var i = 0; i < arguments.length; ++i)
alert(arguments[i]);
}
它就像一个数组,但它不是一个数组.事实上,它太奇怪了,你根本不应该使用它.一种常见的做法是将它的值放入一个真实数组:
It's like an array, but it's not an array. In fact it's so weird that you really shouldn't use it much at all. A common practice is to get the values of it into a real array:
function foo() {
var args = Array.prototype.slice.call(arguments, 0);
// ...
在那个例子中,args"将是一个普通的数组,没有任何奇怪的地方.参数"存在各种令人讨厌的问题,在 ECMAScript 5 中它的功能将被缩减.
In that example, "args" would be a normal array, without any of the weirdness. There are all sorts of nasty problems with "arguments", and in ECMAScript 5 its functionality will be curtailed.
编辑 —尽管使用 .slice()
函数确实很方便,但事实证明,将 arguments
对象传递出函数会导致优化的麻烦,以至于函数执行它可能根本没有得到优化.因此,将 arguments
转换为数组的简单直接的方法是
edit — though using the .slice()
function sure is convenient, it turns out that passing the arguments
object out of a function causes headaches for optimization, so much so that functions that do it may not get optimized at all. The simple, straightforward way to turn arguments
into an array is therefore
function foo() {
var args = [];
for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
// ...
}
这篇关于JavaScript 函数中的无限参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!