Home > Article > Web Front-end > How to Pass an Array as Function Parameters in JavaScript?
Passing an Array as Function Parameter in JavaScript
Passing an array as individual parameters to a function can be tedious and inefficient. Consider the following code:
const x = ['p0', 'p1', 'p2']; call_me(x[0], x[1], x[2]); // Unwieldy and prone to errors
Solution 1: Function.prototype.apply()
To pass an array's contents as parameters, you can use the Function.prototype.apply() method:
const args = ['p0', 'p1', 'p2']; call_me.apply(this, args);
The apply() method takes two parameters: the context and an array of parameters to pass. In this case, this is the function's context, and args is an array of the array's elements.
Solution 2: Spread Arguments (ES6 and above)
If using ECMAScript 6 or higher is feasible, you can use spread arguments instead:
call_me(...args);
Spread arguments allow you to directly pass the contents of an array as parameters without the need for intermediate storage.
The above is the detailed content of How to Pass an Array as Function Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!