开发者

How to create a function and pass in variable length argument list?

开发者 https://www.devze.com 2022-12-29 02:49 出处:网络
We can create a function p in the following code: var p = function() { }; if (typeof(console) != \'undefined\' && console.log) {

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 Chrom开发者_如何学Ce.


You can use Function.apply():

console.log.apply(console, arguments);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号