Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function with the variable number of arguments

Status
Not open for further replies.

DamienD

Programmer
Dec 18, 2006
1
AU
It is often useful to create functions with the variable number of arguments: if the argument is not specified, it automatically gets a default value.

Here is how to do it:

function MyFun(a, b, c)
{
a = (typeof(a) == "undefined") ? false : a;
b = (typeof(b) == "undefined") ? 50 : b;
c = (typeof(c) == "undefined") ? "Some text" : c;

// Do something with a,b,c
}

DamienD
Visit us at
 
Do Microsoft know you've virtually copied wholesale their JScript reference from the MSDN site for your JavaScript reference? You certainly don't credit them anywhere.

You don't even show which JScript is IE-only and which is cross-browser - another dead giveaway that it's a copy/paste job (albeit with a small amount of reformatting).

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 

Here is something interesting

Code:
function fun(){
  var args=fun.arguments;
  for (i=0; i<args.length; i++){
    alert(args[i]);
  }
}

It does work on IE6+, don't know on others. And ok alert may be a bad example but you get the idea.

N

 
if you combine the checking of the ARGS array with a type check, you could end up with a polymorphic function, similar to what Java offers - i.e. the same function with several different params :

function add (x int,y int)
function add (x string, y string)
function add (x real, y real)
function add (x int, .... y int)

could all be accomodated in a single function as discussed here (
Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top