我使用Firebug,并有一些语句像:

console.log("...");

在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

我还是会得到错误。有办法消除错误吗?


当前回答

另一种选择是typeof操作符:

if (typeof console == "undefined") {
    this.console = {log: function() {}};
}

还有一种替代方法是使用日志库,比如我自己的log4javascript。

其他回答

在IE9中,如果控制台未打开,以下代码:

alert(typeof console);

会显示“对象”,但这个代码

alert(typeof console.log);

将抛出TypeError异常,但不返回未定义的值;

因此,保证版本的代码将类似于:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}
if (typeof console == "undefined") {
  this.console = {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}

You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}
console = console || { 
    debug: function(){}, 
    log: function(){}
    ...
}

为了更健壮的解决方案,使用下面的代码(取自twitter的源代码):

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());