Start New Discussion within our Web Development Community


I'm trying to do a loop in javascript, that adds an array into a variable.
Because it is a bit hard to explain exactly what I want, please look at this code, which does the (for the beginning) same.

var s="one, two, three"; //this can be changed
var p=s.split(',');
var l=p.length;

All the if-statements should be replaced by a nice loop.
Anybody has an idea?


fn(p[0], p[1])
fn(p[0], p[1], p[2])...



Does your existing code work? What does fn do?

Troy III's method should work.

I usually go with something less fancy (a plain old for-loop):

for (var i = 0; i < l; i++) {

fn calles a function, and the arrays are its parameters, so you can't call the function 5 times with an other first parameter, you have to add a new.
and yes, my code works, the problem is just it's limited and doesn't look nice...

So you are dynamically changing the number of parameters passed to a function?

Hmmnn. . . I have not seen that before. But that doesn't mean it is not possible. (I am not the world's best Javascript programmer.)

Off the top of my head, perhaps you could create a struct with all the parameters added before the function call. Then, in the function, extract the relevant data as required. Since only the address of a struct is passed into a function, its size doesn't have to be defined before program execution.

Or could you pass tree into the function and split it there?

Hopefully, somebody more knowledgeable than I with regards to Javascipt can suggest a more elegant solution.


fn(p[0], p[1])
fn(p[0], p[1], p[2])...



well, conventionally -that's not doable.
you'll need to write your function on the fly

the fn function can be everything. i want to do a function proo(), where you instead of calling a function directly call this function, which then calles your function.
So imagine, I want to call the function hello().
Instead of hello(); you say proo('hello','');
That's easy, it gets hard with parameters:

function hello(a,b){alert(a + b);} 
proo('hello', 'firstPara, secondPara');

Sounds probably stupid, but I need it.

This article has been dead for over six months. Start a new discussion instead.