Javascript 如何创建函数并传入变长参数列表?
我们可以在以下代码中创建函数Javascript 如何创建函数并传入变长参数列表?,javascript,function,lambda,variadic-functions,Javascript,Function,Lambda,Variadic Functions,我们可以在以下代码中创建函数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], ... 有
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上不起作用。您可以使用:
console.log.apply(console, arguments);