避免调试代码导致IE出错

记录一下

if(!window.console){
    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() {};
    }
}

可以放在基础库里面,当然,注意names和i的作用域~

以上是以前在某个网站上看到的。最近看了 html5 boilerplate 发现了一段新代码,更好

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

这个只会把没有的方法给设置为空函数,而且写法也好于第一种,各种作用域控制的很好。

原文地址:https://www.cnblogs.com/season-huang/p/3632270.html