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

console.log("...");

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

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

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


当前回答

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

其他回答

Try

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

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

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

对于IE8或控制台支持仅限于console.log(没有调试,跟踪,…),您可以执行以下操作:

如果console或console.log未定义:为 控制台函数(跟踪,调试,日志,…) 窗口。控制台= { Debug: function(){},…}; 否则,如果console.log被定义(IE8)和console.debug(任何其他)没有定义:重定向所有日志功能到console.log,这允许保留这些日志! 窗口。控制台= { 调试:window.console.log,…};

不确定在各种IE版本中的assert支持,但欢迎任何建议。也在这里发布了这个答案:我如何在Internet Explorer中使用控制台登录?

注意到OP在IE中使用Firebug,所以假设它是Firebug Lite。当调试器窗口打开时,在IE中定义控制台,这是一种奇怪的情况,但是当Firebug已经在运行时会发生什么呢?不确定,但在这种情况下,"firebugx.js"方法可能是一个很好的测试方法:

来源:

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

    if (!window.console || !console.firebug) {
        var names = [
            "log", "debug", "info", "warn", "error", "assert",
            "dir","dirxml","group","groupEnd","time","timeEnd",
            "count","trace","profile","profileEnd"
        ];
        window.console = {};
        for (var i = 0; i < names.length; ++i)
            window.console[names[i]] = function() {}
    }

(更新链接12/2014)

在我的脚本中,我要么使用速记:

window.console && console.log(...) // only log if the function exists

或者,如果不可能编辑每一个console.log行,我创建一个假控制台:

// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing. 
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.console = {} && window.console.log = function () {});

另一种选择是typeof操作符:

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

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