是否可以向JavaScript函数发送可变数量的参数? [英] Is it possible to send a variable number of arguments to a JavaScript function?

查看:118
本文介绍了是否可以向JavaScript函数发送可变数量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从数组向JavaScript函数发送可变数量的参数?

Is it possible to send a variable number of arguments to a JavaScript function, from an array?

var arr = ['a','b','c']

var func = function()
{
    // debug 
    alert(arguments.length);
    //
    for(arg in arguments)
        alert(arg);
}

func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'
func(arr); // prints 1, then 'Array'

我最近写了很多Python,它是一个美妙的模式,能够接受varargs并发送它们。例如

I've recently written a lot of Python and it's a wonderful pattern to be able to accept varargs and send them. e.g.

def func(*args):
   print len(args)
   for i in args:
       print i

func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'
func(*arr) // prints 4 which is what I want, then 'a','b','c','d'

在JavaScript中是否可以发送数组到将视为参数数组?

Is it possible in JavaScript to send an array to be treated as the arguments array?

推荐答案

使用 apply

var arr = ['a','b','c'];

var func = function() {
  alert(arguments.length);

  for(var i = 0; i < arguments.length; i++) {
    alert(arguments[i]);
  }

};

func.apply(null, arr);

请注意 null 用作第一个apply的参数,将关键字设置为 func 内的全局对象(窗口)。

Notice that null is used as the first argument of apply, that will set the this keyword to the Global object (window) inside func.

另请注意 arguments 对象实际上不是一个数组,你可以将它转换为:

Also note that the arguments object is not really an Array, you can convert it by :

var argsArray = Array.prototype.slice.call(arguments);

也许对你有用,你可以知道一个函数需要多少个参数:

And maybe is useful to you, that you can know how many arguments a function expects:

var test = function (one, two, three) {}; 
test.length == 3;

但无论如何你可以传递任意数量的参数......

But anyway you can pass an arbitrary number of arguments...

这篇关于是否可以向JavaScript函数发送可变数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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