【问题标题】:How to create a function and pass in variable length argument list?如何创建函数并传入可变长度参数列表?
【发布时间】:2010-05-06 04:45:10
【问题描述】:

我们可以在下面的代码中创建一个函数p

var p = function() { };
if (typeof(console) != 'undefined' && console.log) {
    p = function() { console.log(arguments); };
}

但是参数像数组一样传递给console.log,而不是像中一样一个一个地传递

console.log(arguments[0], arguments[1], arguments[2], ... 

有没有办法像上面那样扩展参数并传递给console.log?

注意如果原始代码是

var p = function() { };
if (typeof(console) != 'undefined' && console.log) {
    p = console.log;
}

那么它在 Firefox 和 IE 8 上运行良好,但在 Chrome 上却不行。

【问题讨论】:

    标签: javascript function lambda variadic-functions


    【解决方案1】:

    你可以使用Function.apply():

    console.log.apply(console, arguments);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      相关资源
      最近更新 更多