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

其他回答

在TypeScript中控制台的存根:

if (!window.console) {
console = {
    assert: () => undefined,
    clear: () => undefined,
    count: () => undefined,
    debug: () => undefined,
    dir: () => undefined,
    dirxml: () => undefined,
    error: () => undefined,
    group: () => undefined,
    groupCollapsed: () => undefined,
    groupEnd: () => undefined,
    info: () => undefined,
    log: () => undefined,
    msIsIndependentlyComposed: (e: Element) => false,
    profile: () => undefined,
    profileEnd: () => undefined,
    select: () => undefined,
    time: () => undefined,
    timeEnd: () => undefined,
    trace: () => undefined,
    warn: () => undefined,
    }
};

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

我只使用console.log在我的代码。所以我包括一个很短的2眼线

var console = console || {};
console.log = console.log || function(){};

另一种选择是typeof操作符:

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

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

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

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