gobbly2100
Dec 9th 2007, 11:22 am
Hey,
I am trying to understand this passing arguments business in JavaScript but I just can't seem to grasp it, could someone try and explain it a bit clearer to me if you don't mind?
I have tried using W3 and About.com but just don't get it, am sure it is stupidly simple too.
Thanks!
gobbly2100
Dec 9th 2007, 4:13 pm
Yes, sorry that is what I meant, just confuses me
hrcerqueira
Dec 9th 2007, 5:01 pm
Function arguments in javascript work pretty much like any other languages, a list of values between curly braces and separated by commas. Then there are just a few things you must be aware of.
1 - Arguments are not typecasted, each argument can be of any type, basically as any variable in javascript. Example:
function sum(a, b) {
return a + b;
}
alert(sum(2, 4)); //6
alert(sum('a', 7)); //a7
2 - You can use any number of arguments you want, you don't need to stick to the ones defined in function definition, but obviously, your function must be prepared to deal with that. Example:
function sum(a, b, c) {
var total = 0;
if (a)
total += a;
if (b)
total += b;
if (c)
total += c;
return total;
}
alert(sum(2,3,4)); //9
alert(sum(4,2)); //6
alert(sum(8)); //8
alert(sum()); //0
3 - You can use the special array "arguments" to refer to every argument in a function. Example:
function sum() {
total = 0;
for (var i = 0; i < arguments.length; i++)
total += arguments[i];
return total;
}
alert(sum(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); //10
Hope it helps
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.