问题描述
我可以在 JavaScript 中以方便的方式调用带有参数数组的函数吗?
Can I call a function with array of arguments in a convenient way in JavaScript?
示例:
var fn = function() {
console.log(arguments);
}
var args = [1,2,3];
fn(args);
我需要 arguments
是 [1,2,3]
,就像我的数组一样.
I need arguments
to be [1,2,3]
, just like my array.
推荐答案
自 ES6 引入以来,您可以起诉 扩展语法在函数调用中:
Since the introduction of ES6, you can sue the spread syntax in the function call:
const args = [1,2,3];
fn(...args);
function fn() {
console.log(arguments);
}
在 ES6 之前,您需要使用 apply
.
Before ES6, you needed to use apply
.
var args = [1,2,3];
fn.apply(null, args);
function fn() {
console.log(arguments);
}
两者都会产生等效的函数调用:
Both will produce the equivalent function call:
fn(1,2,3);
请注意,我使用 null
作为 apply
示例的第一个参数,这会将 this
关键字设置为全局对象(window
) 在 fn
或 undefined
中,在严格模式下.
Notice that I used null
as the first argument of the apply
example, which will set the this
keyword to the global object (window
) inside fn
or undefined
under strict mode.
此外,您应该知道 arguments
对象不是数组,而是类似数组的对象,其中包含与用于调用函数的参数相对应的数字索引,一个 length
属性给出您使用的参数数量.
Also, you should know that the arguments
object is not an array, it's an array-like object, that contains numeric indexes corresponding to the arguments that were used to call your function, a length
property that gives you the number of arguments used.
在 ES6 中,如果你想以数组的形式访问可变数量的参数,你也可以使用 rest语法在函数参数列表中:
In ES6, if you want to access a variable number of arguments as an array, you can also use the rest syntax in the function parameter list:
function fn(...args) {
args.forEach(arg => console.log(arg))
}
fn(1,2,3)
在 ES6 之前,如果你想从你的 arguments
对象创建一个数组,你通常使用 Array.prototype.slice
方法.
Before ES6, if you wanted to make an array from your arguments
object, you commonly used the Array.prototype.slice
method.
function fn() {
var args = Array.prototype.slice.call(arguments);
console.log(args);
}
fn(1,2,3);
为了回应您的评论,是的,您可以使用 shift
方法并将其返回值设置为上下文(this
> 关键字)在您的函数上:
In response to your comment, yes, you could use the shift
method and set its returned value as the context (the this
keyword) on your function:
fn.apply(args.shift(), args);
但请记住,shift
将从原始数组中删除第一个元素,并且您的函数将在没有第一个参数的情况下被调用.
But remember that shift
will remove the first element from the original array, and your function will be called without that first argument.
如果您仍然需要使用所有其他参数调用您的函数,您可以:
If you still need to call your function with all your other arguments, you can:
fn.apply(args[0], args);
如果你不想改变上下文,你可以提取函数中的第一个参数:
And if you don't want to change the context, you could extract the first argument inside your function:
function fn(firstArg, ...args) {
console.log(args, firstArg);
}
fn(1, 2, 3, 4)
在 ES5 中,这会更冗长一些.
In ES5, that would be a little more verbose.
function fn() {
var args = Array.prototype.slice.call(arguments),
firstArg = args.shift();
console.log(args, firstArg);
}
fn(1, 2, 3, 4);
这篇关于使用参数数组调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!