我如何打印调试消息在谷歌Chrome JavaScript控制台?

请注意,JavaScript控制台和JavaScript调试器是不一样的;它们有不同的语法AFAIK,所以在JavaScript调试器中的打印命令在这里将不起作用。在JavaScript控制台中,print()会将参数发送给打印机。


当前回答

console.debug("");

使用此方法在控制台中以明亮的蓝色打印文本。

其他回答

简单的Internet Explorer 7及以下,为其他浏览器保留行编号:

/* Console shim */
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());

只是一个简短的警告——如果你想在不删除所有console.log()的情况下在Internet Explorer中测试,你需要使用Firebug Lite,否则你会得到一些不太友好的错误。

(或者创建自己的console.log(),只返回false。)

改进Andru的想法,你可以写一个脚本来创建控制台函数,如果他们不存在:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

然后,使用以下任何一种方法:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

这些函数将记录不同类型的项目(可以根据log, info, error或warn进行过滤),并且在控制台不可用时不会导致错误。这些功能将在Firebug和Chrome控制台中工作。

console.debug("");

使用此方法在控制台中以明亮的蓝色打印文本。

除了Delan Azabani的回答,我还喜欢分享我的console.js,我也是出于同样的目的。我用一个函数名数组创建了一个noop控制台,在我看来这是一种非常方便的方式,我照顾了Internet Explorer,它有一个console.log函数,但没有console.debug:

// Create a noop console object if the browser doesn't provide one...
if (!window.console){
  window.console = {};
}

// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
  if (!window.console.debug && typeof window.console.log !== 'undefined') {
    window.console.debug = window.console.log;
  }
}

// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
  if(!window.console[names[i]]){
    window.console[names[i]] = function() {};
  }
}