javascript_howto thread: Did you know: variable parameters in funcitons...
Hi,
"JavaScript how to" is often a forum where we ASK questions, but I think
that
"how to" can also be turned around: "This is how to!" :-)
I just discovered that the parameter passing in JavaScript is not only
cool,
but really cool!! Just see here:
function myPlot(x, y) {
x = x || 100; // If no x coordinate, set to default: 100
y = y || 100; // If no x coordinate, set to default: 100
var s = '\nWe are plotting in ';
if (myPlot.arguments[2]) {
// We are using 3 coordinates (3D)
var z = myPlot.arguments[2];
s+='3D'
} else {
s+='2D'
}
return (s+'\nat coordinate ('+x+','+y+((z) ? ','+z : '')+')')
}
alert('Calling with 2 coordinates:\nmyPlot(200,300)\n'+myPlot(200,300))
alert('Calling with 1 coordinates:\nmyPlot(200)\n'+myPlot(200)+'\n\nNote
default value for Y!')
alert('Calling with 1 coordinates:\nmyPlot(null,200)\n'+myPlot(null,200)+'
\n\nNote default value for X!!!')
alert('Calling with 3 coordinates:\nmyPlot(null,null,200)\n'+myPlot(null,
null,200)+'\n\nNote default value for X AND Y!!!')
To sum up:
- You can have variable numbers of parameters i JS functions
- You don't have to define them as you construct your "function".
You can access them through "functionnname.arguments[argNoStartFromZero]"
- You can have default values using "||" for instance:
"x = x || defaultValue" (x is a known parameter name!)
I think that this can lead to many new pieces of javascript!
Happy coding!
Cheers,
Sten Hougaard
EDB Gruppen, Denmark