是否有一种方法允许“无限”变量的函数在JavaScript?
例子:
load(var1, var2, var3, var4, var5, etc...)
load(var1)
是否有一种方法允许“无限”变量的函数在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
}
这是大致相同数量的代码(可能稍微多一点),但应该是运行时成本的一小部分。
其他回答
在(大多数)最新的浏览器中,您可以使用以下语法接受可变数量的参数:
function my_log(...args) {
// args is an Array
console.log(args);
// You can pass this array as parameters to another function
console.log(...args);
}
这里有一个小例子:
function foo(x, ...args) {
console.log(x, args, ...args, arguments);
}
foo('a', 'b', 'c', z='d')
=>
a
Array(3) [ "b", "c", "d" ]
b c d
Arguments
0: "a"
1: "b"
2: "c"
3: "d"
length: 4
文档和更多示例请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
另一种选择是在上下文对象中传入参数。
function load(context)
{
// do whatever with context.name, context.address, etc
}
像这样使用它
load({name:'Ken',address:'secret',unused:true})
这样做的好处是,您可以添加任意多的命名参数,并且函数可以根据需要使用(或不使用)它们。
是的,就像这样:
function load()
{
var var0 = arguments[0];
var var1 = arguments[1];
}
load(1,2);
Ramast指出,最好使用rest参数语法。
function (a, b, ...args) {}
我只是想添加一些很好的属性。args参数
它是一个数组,而不是像参数那样的对象。这允许您直接应用map或sort等函数。 它不包括所有参数,而只包括从它传递的一个参数。例如,函数(a, b,…args)在这种情况下args包含 参数3到arguments.length
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
}
这是大致相同数量的代码(可能稍微多一点),但应该是运行时成本的一小部分。