在JavaScript函数的参数无限 [英] Unlimited arguments in a JavaScript function

查看:882
本文介绍了在JavaScript函数的参数无限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否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.

修改的&MDASH;虽然使用 .slice()功能肯定是方便的,事实证明,通过了参数对象从一个函数引起头痛的优化,以至于该做的功能可能不会在所有的优化。简单,直接的方式把参数到一个数组因此

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆