如何在错误控制台中打印消息,最好包括一个变量?
例如,像这样的内容:
print('x=%d', x);
如何在错误控制台中打印消息,最好包括一个变量?
例如,像这样的内容:
print('x=%d', x);
console.log()
等应该在所有浏览器中都可以使用,包括IE。 但是,在所有情况下,你需要在调试器窗口打开时进行调用,否则调用console
将会生成错误。 - Spudleyconsole.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
异常将被记录到JavaScript控制台中。如果您想禁用Firebug,则可以使用它。
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
用法:
log('Hello World');
log('another message');
throw
必须包含在setTimeout
中? - HelloWorld101一个适用于跨浏览器的好方法在 调试JavaScript:放弃您的警报! 中进行了概述。
throw()
绝对不是解决这个问题的方法。你迟早会遇到麻烦。我遇到的时间就比较早,:(。 - Hugo Mota如果你使用Safari,你可以写下以下代码
console.log("your message here");
它会直接显示在浏览器的控制台上。
console.log()
。 - JJJconsole.log()
。 直到最近这并不是真的。 - Bryce以下是如何将消息打印到浏览器错误控制台而非调试器控制台的解决方案(可能会有绕过调试器的好理由)。
关于使用抛出错误以在错误控制台中获取消息的建议,一个问题是这会中断执行线程。如果不想中断线程,则可以在单独的线程中抛出错误,可以使用setTimeout创建一个线程。因此,下面是我的解决方案(实际上是Ivo Danihelka提出的解决方案的详细说明):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
我在日志信息中包含了自启动时间以来的毫秒数,因为超时可能会导致您预期看到的消息顺序发生偏差。
Error方法的第二个参数是用于文件名的,这里设置为空字符串可防止输出无用的文件名和行号。虽然可以获取调用方函数,但无法使用简单的与浏览器无关的方式。
如果我们能够以警告或消息图标的形式显示消息就好了,但我找不到实现的方法。
使用throw的另一个问题是它可能被封闭的try-catch捕获并且被抛弃,在一个单独的线程中放置throw也避免了这个障碍。然而,错误还有另一种被捕获的方式,即如果window.onerror处理程序被替换为执行其他操作的处理程序。对此无能为力。
实际回答问题:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
除了错误,你也可以使用信息、日志或警告。
console.error(..)
是一个非标准功能,不应在生产中使用。你对此有什么看法?你有没有关于新手程序员使用console.error
和console.log
的建议? - modulitos如果您正在使用Firebug,并且需要在IE、Safari或Opera中提供支持,Firebug Lite可以为这些浏览器添加console.log()支持。
WebKit的网页检查器也支持Firebug的控制台API(这只是对Dan's answer的轻微补充)。
一如既往,Internet Explorer 是一个大象穿着轮滑鞋,阻止你简单地使用 console.log()
。
jQuery 的日志 可以很容易地进行适应,但是在每个地方都添加它会很麻烦。如果你正在使用 jQuery,则可以将其放入你的 jQuery 文件末尾,首先进行缩小:
function log()
{
if (arguments.length > 0)
{
// Join for graceful degregation
var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];
// This is the standard; Firebug and newer WebKit browsers support this.
try {
console.log(args);
return true;
} catch(e) {
// Newer Opera browsers support posting erros to their consoles.
try {
opera.postError(args);
return true;
}
catch(e)
{
}
}
// Catch all; a good old alert box.
alert(args);
return false;
}
}