"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Pass an Array as Function Parameters in JavaScript?

How to Pass an Array as Function Parameters in JavaScript?

Published on 2024-11-16
Browse:159

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3