Unknown number of parameters in Javascript
In the previous TutBits post, I showed the technique of functions which take an arbitrary amount of parameters in actionscript. Lately, I needed this feature in javascript. In javascript to each function belongs an array containing ALL parameters. The naming of that array follows the following rule:
functionname.arguments
Since this array is created by default, actually you would not need to declare any parameters anymore. But of course it is more convenient to name parameters in the function signature with a variable name.
However, there might be situations where you do not know the exact amount of parameters which are passed to your function. Have a look at the following piece of code which is the equivalent of the actionscript function of the previous post:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function showFavouriteMovies(name) { var retString = name + "'s favourite movies are: "; // Loop through all arguments starting from index 1. // Note: index 0 contains the value for given explicit parameter 'name' for (var i = 1; i < showFavouriteMovies.arguments.length; i++) { retString += showFavouriteMovies.arguments[i]; // Add comma to list if ( i < (showFavouriteMovies.arguments.length-1) ) { retString += ", "; } } alert(retString + "."); } |
On line #07 you see how to access the functions’ arguments array. We simply loop through it. Remember that we start in our example at index 1. Index 0 contains the first parameter name which equals showFavouriteMovies.arguments[0].
As you can see, functions in javascript with an unknown number of parameters are easily possible, however a big disadvantage in javascript is in my eyes that you cannot judge by a function’s signature if it processes arbitrary parameters or not. In other languages like Actionscript for example an arbitrary amount of parameters are symbolized by a “…args:Array”-parameter in the function signature.
