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

console.log("...");

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

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

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


当前回答

有时控制台可以在IE8/9中工作,但在其他时候会失败。这种不稳定的行为取决于你是否打开了开发工具,并在stackoverflow问题中描述了IE9是否支持console.log,这是一个真实的函数吗?

其他回答

console = console || { 
    debug: function(){}, 
    log: 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) { } };
}

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

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

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

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

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

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