Hey,

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;
if(l==1){fn(p[0]);}
if(l==2){fn(p[0],p[1]);}
if(l==3){fn(p[0],p[1],p[2]);}
if(l==4){fn(p[0],p[1],p[2],p[3]);}
if(l==5){fn(p[0],p[1],p[2],p[3],p[4]);}
......

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

Recommended Answers

All 10 Replies

var p = "one, two, three".split(',')
;for(i in p)fn(p[i]);

Like:

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


not:

fn(p[0])
fn(p[1])
fn(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(p[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.

Like:

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


not:

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

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

OK, I'll stick with the if-statements.

how complicated is the fn function?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.