JavaScript函数中的无限参数

rha*_*avd 41 javascript arrays function

JavaScript函数可以采用无限制的参数吗?像这样的东西:

testArray(1, 2, 3, 4, 5...);
Run Code Online (Sandbox Code Playgroud)

我在尝试:

var arr = [];
function testArray(A) {
    arr.push(A);
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用(输出只是第一个参数).或唯一的方法是:

function testArray(a, b, c, d, e...) {

}
Run Code Online (Sandbox Code Playgroud)

谢谢

Poi*_*nty 57

你可以引用一个奇怪的"魔法"变量叫做"参数":

function manyArgs() {
  for (var i = 0; i < arguments.length; ++i)
    alert(arguments[i]);
}
Run Code Online (Sandbox Code Playgroud)

就像一个数组,但它不是一个数组.事实上,你真的不应该使用它真是太奇怪了.一种常见的做法是将其值转换为实数数组:

function foo() {
  var args = Array.prototype.slice.call(arguments, 0);
  // ...
Run Code Online (Sandbox Code Playgroud)

在那个例子中,"args"将是一个普通的数组,没有任何奇怪的东西."参数"存在各种令人讨厌的问题,而在ECMAScript 5中,其功能将受到限制.

编辑 - 虽然使用.slice()函数肯定很方便,但事实证明,将arguments对象从函数中传递出来会导致优化问题,以至于执行此操作的函数可能根本无法进行优化.因此,arguments变成数组的简单直接的方法

function foo() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  // ...
}
Run Code Online (Sandbox Code Playgroud)

更多关于arguments和优化.

  • 我是诗意的:-)而且"参数"变量*很奇怪 - 它也有"callee"属性. (6认同)
  • 没有任何"神奇"或奇怪的东西,参数对象在ECMA-262中定义.它与数组的唯一相似之处在于它的length属性比其最高数字属性名称多一个.除此之外,它只是一个具有属性的对象. (3认同)
  • 在此详细解释http://stackoverflow.com/questions/5145032/whats-the-use-of-array-prototype-slice-callarray-0 (2认同)

Luc*_*use 20

从ECMAScript 2015(或ES6)开始,我们还可以访问休息参数,这些参数为我们提供了一种更简洁的方法来管理参数:

function foo(a, b, ...others) {
    console.log("a and b are ", a, b);

    for (let val of others) {
        console.log(val);
    }
}

foo(1, 2, 3, 4, 5);
Run Code Online (Sandbox Code Playgroud)

在撰写本文时,Chrome 47 +,Firefox 15+和Edge支持此功能.这个功能也可以通过BabelTypeScript转换到ES5.


Mar*_*edi 5

使用ECMAScript 6,您可以使用其余的参数语法:

const testArray = (...args) => {
    console.log(args);
};

testArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Run Code Online (Sandbox Code Playgroud)