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!!!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With