根据这篇文章,它在测试版中,但它不在发行版中?


当前回答

更好的退路是:


   var alertFallback = true;
   if (typeof console === "undefined" || typeof console.log === "undefined") {
     console = {};
     if (alertFallback) {
         console.log = function(msg) {
              alert(msg);
         };
     } else {
         console.log = function() {};
     }
   }

其他回答

console.log只有在打开开发人员工具(F12来切换它的打开和关闭)后才可用。 有趣的是,在你打开它之后,你可以关闭它,然后仍然通过console.log调用发布到它,这些将在你重新打开它时看到。 我认为这是一个bug,可能会被修复,但我们将拭目以待。

我可能会用这样的东西:

function trace(s) {
  if ('console' in self && 'log' in console) console.log(s)
  // the line below you might want to comment out, so it dies silent
  // but nice for seeing when the console is available or not.
  else alert(s)
}

更简单的是:

function trace(s) {
  try { console.log(s) } catch (e) { alert(s) }
}

我真的很喜欢“orange80”发布的方法。它很优雅,因为你可以设置一次,然后忘记它。

其他方法要求您做一些不同的事情(每次调用console.log()以外的东西),这只是在自找麻烦……我知道我最终会忘记。

我更进一步,通过将代码包装在一个实用函数中,您可以在javascript的开头调用一次,只要是在任何日志记录之前。(我正在我公司的事件数据路由器产品中安装这个。这将有助于简化新管理界面的跨浏览器设计。)

/**
 * Call once at beginning to ensure your app can safely call console.log() and
 * console.dir(), even on browsers that don't support it.  You may not get useful
 * logging on those browers, but at least you won't generate errors.
 * 
 * @param  alertFallback - if 'true', all logs become alerts, if necessary. 
 *   (not usually suitable for production)
 */
function fixConsole(alertFallback)
{    
    if (typeof console === "undefined")
    {
        console = {}; // define it if it doesn't exist already
    }
    if (typeof console.log === "undefined") 
    {
        if (alertFallback) { console.log = function(msg) { alert(msg); }; } 
        else { console.log = function() {}; }
    }
    if (typeof console.dir === "undefined") 
    {
        if (alertFallback) 
        { 
            // THIS COULD BE IMPROVED… maybe list all the object properties?
            console.dir = function(obj) { alert("DIR: "+obj); }; 
        }
        else { console.dir = function() {}; }
    }
}

这是我的“IE,请不要崩溃”

typeof console=="undefined"&&(console={});typeof console.log=="undefined"&&(console.log=function(){});

我使用沃尔特的方法从上面(见:https://stackoverflow.com/a/14246240/3076102)

我在这里找到了一个解决方案https://stackoverflow.com/a/7967670来正确地显示对象。

这意味着trap函数变成:

function trap(){
    if(debugging){
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
            }
        }
        var message = args.join(' ');
        console.messages.push(message);
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
        if($){
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));
        }
    }
} 

我希望这对你有帮助:-)

我在github上找到了这个:

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f() {
    log.history = log.history || [];
    log.history.push(arguments);
    if (this.console) {
        var args = arguments,
            newarr;
        args.callee = args.callee.caller;
        newarr = [].slice.call(args);
        if (typeof console.log === 'object') log.apply.call(console.log, console, newarr);
        else console.log.apply(console, newarr);
    }
};

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