调用函数与参数数组 [英] Call function with array of arguments

查看:115
本文介绍了调用函数与参数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以打电话与参数数组的函数在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);

我需要参数 [1,2,3] ,就像我的数组。

推荐答案

您应该使用<一个href=\"https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference%3AGlobal%5FObjects%3AFunction%3Aapply\"><$c$c>apply:

var fn = function() {
    console.log(arguments);
};

var args = [1,2,3];

fn.apply(null, args);

应用将使相当于函数调用:

Apply will make the equivalent function call:

fn(1,2,3);

请注意,我用适用,将设置这个关键字全局对象(窗口)内 FN

Notice that I used null as the first argument of apply, that will set the this keyword to the global object (window) inside fn.

您也应该知道,在<一个href=\"https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Functions/arguments\"><$c$c>arguments对象是不是一个真正的数组,这是一个类似数组的对象,包含对应于被用来调用你的函数,这给你一个长度属性参数数值索引参数的数目使用,而<一个href=\"https://developer.mozilla.org/En/Core%5FJavaScript%5F1.5%5FReference/Functions%5Fand%5Ffunction%5Fscope/arguments/callee\"><$c$c>arguments.callee属性,是对执行的函数的引用(匿名函数的递归有用)。

Also you should know that the arguments object is not really 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, and the arguments.callee property that is a reference to the executing function (useful for recursion on anonymous functions).

如果您想从论据是一个数组对象,你可以使用 Array.prototype.slice 方法:

If you want to make an array from your arguments object, you can use the Array.prototype.slice method:

var fn = function() {
  var args = Array.prototype.slice.call(arguments);
  console.log(args);
};

编辑:在回答您的意见,是的,你可以使用方法,并将其返回值作为上下文(<你的函数code>这个关键字):

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);

但请记住,将从原来的数组中删除第一个元素,你的功能将不首先参数调用。

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 simply extract the first argument inside your function:

var fn = function() {
  var args = Array.prototype.slice.call(arguments),
      firstArg = args.shift();

  console.log(args, firstArg);
};

这篇关于调用函数与参数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆