Problem
I’d want to use an array as parameters to invoke a function:
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 more efficient way to pass the contents of x to call me()?
Asked by Robert
Solution #1
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
Function.prototype.apply is documented in MDN ().
You can use a spread argument instead if your environment supports ECMAScript 6:
call_me(...args);
Answered by KaptajnKold
Solution #2
Why don’t you provide the complete array to the method and process it as needed?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
Answered by Karl Johan
Solution #3
There is a new spread operator in the ES6 standard… that achieves exactly that.
call_me(...x)
Except for Internet Explorer, it is supported by all major browsers.
The spread operator can be used for a variety of additional purposes, as the attached material demonstrates.
Answered by BoltKey
Solution #4
You don’t expect this to be set because call me is a global function.
var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);
Answered by plexer
Solution #5
As @KaptajnKold had already stated,
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
You also don’t have to define all of the parameters for the call me function. You can simply rely on arguments.
function call_me () {
// arguments is a array consisting of params.
// arguments[0] == 'p0',
// arguments[1] == 'p1',
// arguments[2] == 'p2'
}
Answered by 徐竟峰
Post is based on https://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript