如何创建一个函数并传入可变长度参数列表? [英] How to create a function and pass in variable length argument list?

查看:106
本文介绍了如何创建一个函数并传入可变长度参数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但参数像数组一样传递给控制台.log ,而不是像

中一个一个地传递

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

有没有办法展开参数并传递给console.log,如上所述?



请注意,如果原始代码为

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

然后在Firefox和IE 8上运行良好但不是在Chrome上。 解决方案

您可以使用 Function.apply()

 控制台.log.apply(console,arguments); 


We can create a function p in the following code:

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

but the arguments are passed like an array to console.log, instead of passed one by one as in

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

Is there a way to expand the arguments and pass to console.log like the way above?

Note that if the original code were

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

then it works well on Firefox and IE 8 but not on Chrome.

解决方案

You can use Function.apply():

console.log.apply(console, arguments);

这篇关于如何创建一个函数并传入可变长度参数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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