是否有一种方法允许“无限”变量的函数在JavaScript?
例子:
load(var1, var2, var3, var4, var5, etc...)
load(var1)
是否有一种方法允许“无限”变量的函数在JavaScript?
例子:
load(var1, var2, var3, var4, var5, etc...)
load(var1)
当前回答
另一种选择是在上下文对象中传入参数。
function load(context)
{
// do whatever with context.name, context.address, etc
}
像这样使用它
load({name:'Ken',address:'secret',unused:true})
这样做的好处是,您可以添加任意多的命名参数,并且函数可以根据需要使用(或不使用)它们。
其他回答
当然,只要使用arguments对象。
function foo() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
在函数中使用arguments对象可以访问传入的所有参数。
使用数组,然后你可以使用你需要的参数。例如,计算数组中元素个数的平均值:
function fncAverage(sample) {
var lenghtSample = sample.length;
var elementsSum = 0;
for (var i = 0; i < lenghtSample; i++) {
elementsSum = Number(elementsSum) + Number(sample[i]);
}
average = elementsSum / lenghtSample
return (average);
}
console.log(fncAverage([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); // results 5.5
let mySample = [10, 20, 30, 40];
console.log(fncAverage(mySample)); // results 25
//try your own arrays of numbers
在(大多数)最新的浏览器中,您可以使用以下语法接受可变数量的参数:
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
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
}
这是大致相同数量的代码(可能稍微多一点),但应该是运行时成本的一小部分。