Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Sending comma separated string of parameters to a javascript function

Tags:

javascript

I am having a function in javascript as

function add(v1,v2){

var add=v1+v2;

}

Now I am calling this function as below -

write.out(var param="1,2";);

write.out(window[add](param););

Using the above call, it's not working. What it does is it gives the complete string "1,2" as value to the first param(v1) of the function.

Its working if I call the function in following way -

write.out(var param1="1";);

write.out(var param2="2";);

write.out(window[add](param1,param2););

I want to achieve it using the first way where i can send the parameters as a comma separated string of parameters.

Can some one help me out how this can be done...

Thanks!!!

like image 469
azhar_salati Avatar asked Nov 18 '11 09:11

azhar_salati


1 Answers

You can make usage of ECMAscripts .apply(), which calls a function and accepts an array of paramters.

window['add'].apply(null, param.split(','));

That way, we execute the add function, setting its context to null (you could also change that if you need) and pass in the two paramters. Since we need an Array, we call split() on the string before.

So basically, the above line is the same as

add(1,2);

Since you're haveing that function in the global context (window), we don't even need to write it that explicitly.

add.apply(null, param.split(','));

will just be fine.

like image 141
jAndy Avatar answered Nov 19 '22 16:11

jAndy