Is there a way to allow "unlimited" vars for a function in javascript?
Example: load(var1, var2, var3, var4, var5 etc) and load(var1)
Tom
Is there a way to allow "unlimited" vars for a function in javascript?
Example: load(var1, var2, var3, var4, var5 etc) and load(var1)
Tom
Sure, just use the arguments
parameter.
function foo() {
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
}
}
Use the arguments object when in the function to have access to all arguments passed in.
Yes, just like this :
function load()
{
var var0 = arguments[0];
var var1 = arguments[1];
}
load(1,2);
Another option is to pass in your arguments in a context object.
function load(context)
{
// do whatever with context.name, context.address, etc
}
and use it like this
load({name:'Ken',address:'secret',unused:true})
This has the advantage that you can add as many named arguments as you want, and the function can use them (or not) as it sees fit.