views:

211

answers:

2

I have an array that I need to unpack.

So, from something like

var params = new Array();
params.push("var1");
params.push("var2");

I need to have something like

"var1", "var2".

I tried using eval, but eval() gives me something like var1, var2...i don't want to insert quotes myself as the vars passed can be integers, or other types. I need to pass this to a function, so that's why i can't just traverse the array and shove it into a string.

What is the preferred solution here?

+2  A: 

If you have an array of values that you want to pass to a function filling the formal parameters then you can use the apply method of the Function prototype.

var arr = [1, 2, "three"];

function myFunc(a, b, c) {
   // a = 1, b = 2, c = "three"
   ...
}

myFunc.apply(this, arr);

By the way, the this parameter in the last statement can be set to any object to set the value of this inside myFunc

Sean Kinsey
thanks, I never knew of apply's existence. However, what's the purpose of this here? I am not quite clear regarding "this". Do I need it?
gnomixa
You need *something* there, if you are uncertain use `this` to keep the current context, or pass `null` to use the global context. As I said, the first parameter controls what `this` *inside* the function refers to.
Sean Kinsey
great, this is exactly what I needed. Thanks, Sean!
gnomixa
A: 

This generates the output you want

var params = new Array();
params.push("var1");
params.push("var2");

var s = "\"" + params.join("\",\"") + "\"";
BrunoLM