Javascript:功能的"无限"参数?

use*_*294 36 javascript parameters function infinite

在Chrome中,当我输入console.log以下内容时:

console.log("A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter");
Run Code Online (Sandbox Code Playgroud)

...它正确打印,没有错误或警告.我添加了更多参数,但它仍然正确打印出来.

console.log("A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter");
Run Code Online (Sandbox Code Playgroud)

我怎样才能拥有一个"无限"参数函数呢?

hug*_*omg 55

函数可以访问一个类似于数组的对象arguments,该对象包含它们收到的所有参数

function print_my_arguments(/**/){
    var args = arguments;
    for(var i=0; i<args.length; i++){
        console.log(args[i]);
    }
};
Run Code Online (Sandbox Code Playgroud)

您可以使用apply方法执行相反的转换(使用参数列表调用函数):

// These are equivalent:
print_my_arguments(1,2,3);
print_my_arguments.apply(null, [1,2,3]);

// The first parameter to `apply` is the `this`.
// It is used when the function is a method.
foo.bar(1,2,3);
var f = foo.bar; f.apply(foo, [1,2,3]);
Run Code Online (Sandbox Code Playgroud)

需要注意的一些要点:

  1. arguments不是一个实际的数组,它没有通常的数组方法(切片,连接等).您可以使用以下行将其转换为数组:

    var args = Array.prototype.slice.call(arguments);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果您希望数组仅包含已接收的非命名参数,则切片也很有用:

    function foo(first_arg, second_arg /**/){
        var variadic_args = Array.prototype.slice.call(arguments, 2);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 并非每个浏览器都可以处理任意大量的函数参数.上次我测试了这个,在Chrome和IE中有一些堆栈溢出后,有200.000个参数.如果您的函数可以接收任意大量的参数,请考虑将所有这些参数打包在常规数组中.

  4. /**/出现在我的示例的参数列表中的那些注释不是强制性的.它们只是一种编码惯例,用于标记我的可变参数函数并将它们与常规函数区分开来.

    // A quick glance would suggest that this function receives no
    // parameters but actually it is a variadic function that gets
    // its parameters via the `arguments` object.
    function foo(){
        console.log(arguments.length);
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 对于今年或以后来到这里的任何人,请注意,休息参数现在是执行此操作的首选方式。请参阅下面 Felix Edelmann 的回答。 (2认同)

Fel*_*ann 22

这样做的现代方法是使用rest 参数

function printArguments(...args) {
  args.forEach((arg, index) => {
    console.log(`Argument ${index}:`, arg);
  });
}

printArguments('hello', true, new Date());
Run Code Online (Sandbox Code Playgroud)

通过使用该...args语法,所有参数都保存在名为 的数组中args

除 Internet Explorer 外,所有浏览器都已在其最新版本中提供此功能。

小提琴:https : //jsfiddle.net/Lbf0stst/