我如何打印消息到错误控制台,最好包括一个变量?

例如,像这样:

print('x=%d', x);

当前回答

console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.

你也可以添加CSS:

console.log('%c My message here', "background: blue; color: white; padding-left:10px;");

更多信息可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/API/console

其他回答

最简单的方法是:

console.warn("Text to print on console");

异常被记录到JavaScript控制台。如果你想禁用Firebug,你可以使用它。

function log(msg) {
    setTimeout(function() {
        throw new Error(msg);
    }, 0);
}

用法:

log('Hello World');
log('another message');

在《调试JavaScript:扔掉你的提醒!》中概述了一种跨浏览器的好方法。

关于上面提到的'throw()'的注意事项。它似乎完全停止了页面的执行(我在IE8中检查了),所以它对于记录“正在进行的进程”并不是很有用(比如跟踪某个变量……)

我的建议是在文档的某个地方添加一个textarea元素,并在需要时更改(或追加)它的值(这将更改其文本)以记录信息…

使用es6语法,你可以使用:

console.log(`x = ${x}`);