26

In Javascript I have simple test code:

function x(a, b) {
  alert(a);
  alert(b);
}

var c = [1,2];
x(c);

which send an argument c to function x() as one argument, assigned to a and b stays undefined :-/

How can I send an array as multiple arguments to a function, not as one array?

5
  • Why are you wrapping them in an array in the first place if you don't want an array? Just do x(1,2) Commented Jul 17, 2012 at 23:38
  • 8
    @TheZ I'm sure this is just an example Commented Jul 17, 2012 at 23:39
  • @JuanMendes Alright, then maybe x(c[0],c[1])? I guess I just don't understand what is required. Commented Jul 17, 2012 at 23:40
  • 2
    @TheZ Usually, because you don't know how many arguments you need to pass. That's why Function.apply exists Commented Jul 17, 2012 at 23:41
  • @JuanMendes Oh I see! I guess since the problem said nothing about variable sized arrays I didn't get that at all. Thanks Commented Jul 17, 2012 at 23:43

2 Answers 2

24

Check out apply.

In your case (since you aren't using this in the function), you can simply pass window (or this) as the "this" argument:

x.apply(this, [1, 2]);

Example: http://jsfiddle.net/MXNbK/2/

Per your question about passing null as the "this" argument, see MDN's comment in the linked article on the "this" argument:

Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

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

7 Comments

Would not be nicer to pass null as the first argument, as this has nothing related to such function(ality)...?
You could, but I believe this will still be window inside of the function.
@Ωmega Some browsers break when you pass null as this, even if not used
@JuanMendes - Ooops, really? I believe they should not, but okay... How about zero 0 - would that be acceptable for all browsers?
@Ωmega 0 wouldn't hurt, but why not just pass this? What is the advantage to passing anything else?
|
24

Or, in browsers with ECMAScript 2015 (or with Babel transpiler), you can use the new spread operator:

x(...[1, 2])

2 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
@dev-null This is a valid answer to the question. In ES6 the spread operator works very much like Function.apply.

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.