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