Link to home
Get AccessLog in
Avatar of toddhd

asked on

Passing unlimited params to a javascript function

I need to know how to pass unknown/unlimited parameters to a javascript function. What I want to do is make a simple function that will concatenate any strings passed to a comma delimted string, and then return that string. For example:
var commaDelimitedString = getConcat('dog','cat',bird');
Ok, silly example, but I might pass three string, I might pass 100, who knows? So how do I write the function to accept any number of params and then act on them?
I know I saw something once like this:
function someFunction(...) {
And then the params are acted on as an array, but for the life of me ,I can't figure out the correct Google search terms to find it. Any help would be greatly appreciated.
Avatar of dakyd

There is an arguments function that was meant for that use, but I believe it is deprecated.

Actually, question for you.  Where are all these strings coming from?  Are they already stored in an array?  If so, you don't need a separate function, you can just use join():

<script type="text/javascript">
var strArray = new Array("hello","there","world");
var str = strArray.join(" ");

The argument to join() is what you stick between the values of the array.  I used a space to make it look like a sentence, but in your case you'd probably want to use a comma.  Hope that helps.
Oops, mis-typed ... it's not an arguments function, it's a parameter that was available within the function call.
Avatar of toddhd


Ah, I think this might be what you were talking about:
Avatar of Pravin Asar
function buildString() {
var str = "";
for(var i = 0; i < arguments.length; i++)
str += arguments[i];
if ( (i+1) < arguments.length) { str += ','; }
alert (str);
return str;

buildString ("Alligator", "Bat", "Cat", "Dog");
Avatar of Pravin Asar
Pravin Asar
Flag of United States of America image

Link to home
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Thanks for quick closure and grades.