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

console.log("...");

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

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

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


当前回答

如果你在IE8中打开了开发人员工具,你可以使用Console .log(),也可以使用脚本选项卡上的控制台文本框。

其他回答

为了更健壮的解决方案,使用下面的代码(取自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;
        }
    }
}());

在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() {};
}

另一种选择是typeof操作符:

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

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

Try

if (!window.console) console = ...

未定义的变量不能直接引用。但是,所有全局变量都是全局上下文(浏览器为窗口)同名的属性,访问未定义的属性是可以的。

或者使用if (typeof console === 'undefined') console =…如果你想避开神奇的变量窗口,请参阅@Tim Down的回答。

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) { } };
}