views:

135

answers:

4

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

+10  A: 

Sure, just use the arguments parameter.

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    alert(arguments[i]);
  }
}
roufamatic
thank you! it works
Tom
A: 

Use the arguments object when in the function to have access to all arguments passed in.

nickyt
+2  A: 

Yes, just like this :

function load()
{
  var var0 = arguments[0];
  var var1 = arguments[1];
}

load(1,2);
Canavar
+3  A: 

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.

Ken