Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send array to function as multiple arguments?

Tags:

javascript

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?

like image 225
Ωmega Avatar asked Jul 17 '12 23:07

Ωmega


People also ask

How do you pass an entire array to a function as an argument?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

How do you pass multiple parameters to a function?

Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

Can we pass an array as argument to a function?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.

How do you pass an array as an argument to a function in JavaScript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.


1 Answers

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.

like image 168
Andrew Whitaker Avatar answered Oct 18 '22 09:10

Andrew Whitaker