Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array as a function parameter in JavaScript

I'd like to call a function using an array as parameters:

const x = ['p0', 'p1', 'p2'];
call_me(x[0], x[1], x[2]); // I don't like it

function call_me (param0, param1, param2 ) {
  // ...
}

Is there a better way of passing the contents of x into call_me()?

like image 452
Robert Avatar asked May 18 '10 09:05

Robert


People also ask

How do you pass an array as a function parameter 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.

Can we pass an array in function as a parameter?

Arrays are declared and initialized before using them in a program. In C/C++ an array when passed as a function argument is always treated as a pointer by a function. Ways to pass an array to a function in C/C++ are Formal parameters as pointers, Formal parameters as sized arrays, Formal parameters as unsized arrays.

Can you pass an array in JavaScript?

Use the apply() Method to Pass an Array to a Function in JavaScript. In the example given above, we have an array of names and a function named displayName() to print all elements of the names array. We use apply() method to pass an array to displayName() function.

How do you pass an array to a function?

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.


10 Answers

const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);

See MDN docs for Function.prototype.apply().


If the environment supports ECMAScript 6, you can use a spread argument instead:

call_me(...args);
like image 173
KaptajnKold Avatar answered Oct 01 '22 09:10

KaptajnKold


Why don't you pass the entire array and process it as needed inside the function?

var x = [ 'p0', 'p1', 'p2' ]; 
call_me(x);

function call_me(params) {
  for (i=0; i<params.length; i++) {
    alert(params[i])
  }
}
like image 25
Karl Johan Avatar answered Oct 02 '22 09:10

Karl Johan


In ES6 standard there is a new spread operator ... which does exactly that.

call_me(...x)

It is supported by all major browsers except for IE.

The spread operator can do many other useful things, and the linked documentation does a really good job at showing that.

like image 39
BoltKey Avatar answered Oct 03 '22 09:10

BoltKey


Assuming that call_me is a global function, so you don't expect this to be set.

var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);
like image 26
plexer Avatar answered Oct 02 '22 09:10

plexer


As @KaptajnKold had answered

var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);

And you don't need to define every parameters for call_me function either. You can just use arguments

function call_me () {
    // arguments is a array consisting of params.
    // arguments[0] == 'p0',
    // arguments[1] == 'p1',
    // arguments[2] == 'p2'
}
like image 36
徐竟峰 Avatar answered Oct 02 '22 09:10

徐竟峰


While using spread operator we must note that it must be the last or only parameter passed. Else it will fail.

function callMe(...arr){ //valid arguments
    alert(arr);
}

function callMe(name, ...arr){ //valid arguments
    alert(arr);
}

function callMe(...arr, name){ //invalid arguments
    alert(arr);
}

If you need to pass an array as the starting argument you can do:

function callMe(arr, name){
    let newArr = [...arr];
    alert(newArr);
}
like image 33
Naba Avatar answered Oct 04 '22 09:10

Naba


Function arguments may also be Arrays:

function foo([a,b,c], d){
  console.log(a,b,c,d);
}

foo([1,2,3], 4)

of-course one can also use spread:

function foo(a, b, c, d){
  console.log(a, b, c, d);
}

foo(...[1, 2, 3], 4)
like image 24
vsync Avatar answered Oct 04 '22 09:10

vsync


Note this

function FollowMouse() {
    for(var i=0; i< arguments.length; i++) {
        arguments[i].style.top = event.clientY+"px";
        arguments[i].style.left = event.clientX+"px";
    }

};

//---------------------------

html page

<body onmousemove="FollowMouse(d1,d2,d3)">

<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>


</body>

can call function with any Args

<body onmousemove="FollowMouse(d1,d2)">

or

<body onmousemove="FollowMouse(d1)">
like image 38
ali.b.y Avatar answered Oct 05 '22 09:10

ali.b.y


you can use the spread syntax

for example:

function print(...inpu){
console.log(...inpu)
}
var arry = ['p0','p1','p2']
print(...arry)
here is the link: modzilla spread syntax refrence document
like image 29
Ashton Drye Avatar answered Oct 03 '22 09:10

Ashton Drye


you can use spread operator in a more basic form

[].concat(...array)

in the case of functions that return arrays but are expected to pass as arguments

Example:

function expectArguments(...args){
  return [].concat(...args);
}

JSON.stringify(expectArguments(1,2,3)) === JSON.stringify(expectArguments([1,2,3]))

like image 26
rman Avatar answered Oct 04 '22 09:10

rman