Passing Variable Arguments to JavaScript Functions from Arrays
In JavaScript, it is possible to pass a variable number of arguments to a function, including from an array.
Using the Spread Syntax (ES6)
Since ES6, the spread operator (...) can be used to pass an array's elements as individual arguments to a function:
func(...arr);
Using the rest Parameter (ES6)
If you expect to treat the arguments as an array, you can use the rest parameter:
function func(...args) { args.forEach(arg => console.log(arg)) } func(...values)
Using apply
Another method to pass an array as arguments is to use the apply() method:
func.apply('test', arr);
Note that in non-strict mode, using null as the first argument will cause 'this' in the function to refer to the window object.
Converting the Arguments Object to an Array
The arguments object is not an array, but it can be converted using:
const argsArray = [...arguments];
Additional Notes
In summary, using the spread syntax is the preferred method for passing variable arguments from an array to a JavaScript function, due to its concise syntax and ease of use.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!