1

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?

5
  • I doubt you can get JavaScript to add the " itself, unless maybe you use JSON.stringify(). " are just the string delimiters and do not belong to the string value. Commented May 25, 2010 at 22:06
  • that's the thing, is that i would like to pass the VALUES of the vars...they may not always be strings either. I am wondering if it's possible at all. Commented May 25, 2010 at 22:16
  • How do you want "other types" to be serialised? Commented May 25, 2010 at 22:17
  • 1
    When you say "pass the values"... where are you passing to? Commented May 25, 2010 at 22:18
  • I'm trying to come up with a general solution, so at the point of passing I won't know how many parameters the function will accept. Hence, I shove them into the array. Then, I need to unpack and pass them. So the variables shoved into the array may all be different types:strings, ints, other arrays. When unpacking, I want to be able to do something like: DoSomething(param1, param2, param3) where param1 .. param3 come from the array. I posted here: stackoverflow.com/questions/2836037/… got no real answers Commented May 25, 2010 at 22:27

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
0

This generates the output you want

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.