Javascript 通过代理函数将参数作为第一类参数传递给console.log

Javascript 通过代理函数将参数作为第一类参数传递给console.log,javascript,Javascript,console.log接受未指定数量的参数,并将其内容转储到一行中 是否有一种方法可以编写一个函数,将传递给它的参数直接传递给console.log,以保持这种行为?例如: function log(){ if(console){ /* code here */ } } 这与以下情况不同: function log(){ if(console){ console.log(arguments); } } function log(

console.log
接受未指定数量的参数,并将其内容转储到一行中

是否有一种方法可以编写一个函数,将传递给它的参数直接传递给
console.log
,以保持这种行为?例如:

function log(){
    if(console){
        /* code here */
    }
}
这与以下情况不同:

function log(){
    if(console){
        console.log(arguments);
    }
}
function log(){
    if(console){
        for(i=0;i<arguments.length;console.log(arguments[i]),i++);
    }
}
因为
arguments
是一个数组,
console.log
将转储该数组的内容。也不会与以下内容相同:

function log(){
    if(console){
        console.log(arguments);
    }
}
function log(){
    if(console){
        for(i=0;i<arguments.length;console.log(arguments[i]),i++);
    }
}
函数日志(){
if(控制台){
对于(i=0;iYes)

尽管您可能需要循环arguments对象并从中创建一个常规数组,但除此之外,您还需要这样做。

这应该可以做到

function log() {
    if(typeof(console) !== 'undefined') {
        console.log.apply(console, arguments);
    }
}

只需添加另一个选项(使用运算符和参数-尽管
参数可以直接用于排列)


HTML5样板代码中有一个很好的例子,它以类似的方式包装console.log,以确保不会中断任何不识别它的浏览器。它还添加了历史记录,并消除了console.log实现中的任何差异

它是由Paul Irish开发的,他已经写了一篇关于它的帖子

我已经在下面粘贴了相关代码,下面是指向项目中文件的链接:


这在Chrome/Safari中不起作用。它抛出了一个“非法调用”错误。@aditya,更新的代码..我没有使用正确的上下文..您需要传递
控制台
,作为要应用的
参数..需要指出的是,在脚本中使用此参数仍然会导致IE9或更早版本中的错误(如果您没有使用
标记,甚至IE10)在第一次调用
log();
而不是
if(控制台)
时中断脚本。您应该执行
if(控制台)!='undefined')
适用于新旧浏览器,包括IE6-IE11。更新了答案以使用@purefusion指出的typeof。没有缺点缺少a{before console.log.apply这在Chrome/Safari中不起作用。它适用于Firebug,但在此处寻找跨浏览器解决方案。
args=[];for(i=0;无法使用。显然,对
console.log.apply
的任何调用都会引发非法调用错误。好吧,如果您尝试
console.log(args.join(“”));
而不是我最后一段代码中的
console.log.apply
,那不是我想要的。如果有人尝试
log({})
,它会说
[object object object]
而不是通常的情况。
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}}((function(){try {console.log();return window.console;}catch(err){return window.console={};}})());