是否有一种方法允许“无限”变量的函数在JavaScript?

例子:

load(var1, var2, var3, var4, var5, etc...)
load(var1)

当前回答

Although I generally agree that the named arguments approach is useful and flexible (unless you care about the order, in which case arguments is easiest), I do have concerns about the cost of the mbeasley approach (using defaults and extends). This is an extreme amount of cost to take for pulling default values. First, the defaults are defined inside the function, so they are repopulated on every call. Second, you can easily read out the named values and set the defaults at the same time using ||. There is no need to create and merge yet another new object to get this information.

function load(context) {
   var parameter1 = context.parameter1 || defaultValue1,
       parameter2 = context.parameter2 || defaultValue2;

   // do stuff
}

这是大致相同数量的代码(可能稍微多一点),但应该是运行时成本的一小部分。

其他回答

Ramast指出,最好使用rest参数语法。

function (a, b, ...args) {}

我只是想添加一些很好的属性。args参数

它是一个数组,而不是像参数那样的对象。这允许您直接应用map或sort等函数。 它不包括所有参数,而只包括从它传递的一个参数。例如,函数(a, b,…args)在这种情况下args包含 参数3到arguments.length

当然,只要使用arguments对象。

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

在函数中使用arguments对象可以访问传入的所有参数。

Although I generally agree that the named arguments approach is useful and flexible (unless you care about the order, in which case arguments is easiest), I do have concerns about the cost of the mbeasley approach (using defaults and extends). This is an extreme amount of cost to take for pulling default values. First, the defaults are defined inside the function, so they are repopulated on every call. Second, you can easily read out the named values and set the defaults at the same time using ||. There is no need to create and merge yet another new object to get this information.

function load(context) {
   var parameter1 = context.parameter1 || defaultValue1,
       parameter2 = context.parameter2 || defaultValue2;

   // do stuff
}

这是大致相同数量的代码(可能稍微多一点),但应该是运行时成本的一小部分。

另一种选择是在上下文对象中传入参数。

function load(context)
{
    // do whatever with context.name, context.address, etc
}

像这样使用它

load({name:'Ken',address:'secret',unused:true})

这样做的好处是,您可以添加任意多的命名参数,并且函数可以根据需要使用(或不使用)它们。