Console

您正在阅读此内容的英文版本,因为该语系尚未翻译。 帮助我们翻译此文章吧!

Console 对象可以接入浏览器控制台(如:Firefox 的 Web Console)。在不同浏览器上它的实现细节可能是不一样的,但这里会介绍一些典型的浏览器会提供的特性。

Console 对象可以从任何全局对象中访问到,如 WindowWorkerGlobalScope 以及控制台属性中的特殊变量。它被定义为 Window.console,而且可直接通过 console 调用。例:

console.log("Failed to open the specified link")

本页面记录了 Console 对象中的 Methods 并给出了几个 Usage 示例。

Note: 此特性在 Web Worker 中可用。

提示: 由于历史原因,console 接口全部被定义为小写(在 i.e. 上不能使用 Console)

方法

Console.assert()
判断第一个参数是否为真,false 的话抛出异常并且在控制台输出相应信息。
Console.clear()
清空控制台,并输出 Console was cleared
Console.count()
以参数为标识记录调用的次数,调用时在控制台打印标识以及调用次数。
Console.countReset()
重置指定标签的计数器值。
Console.debug()
在控制台打印一条 "debug" 级别的消息。
提示: 从 Chromium 58 开始,Chromium 浏览器打印的debug消息仅在日志级别为 “Verbose” 时可见。
Console.dir()
打印一条以三角形符号开头的语句,可以点击三角展开查看对象的属性。This listing lets you use disclosure triangles to examine the contents of child objects.
Console.dirxml()
打印 XML/HTML 元素表示的指定对象,否则显示 JavaScript 对象视图。
Console.error()
打印一条错误信息,使用方法可以参考 string substitution
Console.exception()
error() 方法的别称。
Console.group()
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
Console.groupCollapsed()
创建一个新的内联 group。使用方法和 group() 相同,不同的是,groupCollapsed() 方法打印出来的内容默认是折叠的。To move back out a level, call groupEnd().
Console.groupEnd()
Exits the current inline group.
Console.info()
Informative logging of information. You may use string substitution and additional arguments with this method.
Console.log()
For general output of logging information. You may use string substitution and additional arguments with this method.
Console.profile()
Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
Console.profileEnd()
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
Console.table()
将列表型的数据打印成表格。
Console.time()
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
Console.timeEnd()
结束特定的计时器 and logs the elapsed time in seconds since it started。
Console.timeLog()
Logs the value of the specified timer to the console.
Console.timeStamp()
添加一个标记到浏览器的 Timeline 或 Waterfall 工具。
Console.trace()
输出一个 stack trace
Console.warn()
打印一个警告信息,可以使用 string substitution 和额外的参数。

用法

输出文本到控制台

console 对象中较多使用的主要有四个方法 console.log(), console.info(), console.warn(), 和console.error()。每一个结果在日志中都有不同的样式,可以使用浏览器控制台的日志筛选功能筛选出感兴趣的日志信息。

有两种途径使用这些方法,你可以简单的传入一组对象,其中的字符串对象会被连接到一起,输出到控制台。或者你可以传入包含零个或多个的替换的字符串,后面跟着被替换的对象列表。

打印单个对象

The simplest way to use the logging methods is to output a single object:

var someObject = { str: "Some text", id: 5 };
console.log(someObject);

打印结果类似下面:

[09:27:13.475] ({str:"Some text", id:5})

打印多个对象

你可以打印多个对象,就像下面一样:

var car = "Dodge Charger";
var someObject = { str: "Some text", id: 5 }; 
console.info("My first car was a", car, ". The object is:", someObject);

打印结果类似下面:

[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})

使用字符串替换

你可以在传递给 console 的方法的时候使用下面的字符以期进行参数的替换。

Substitution string Description
%o or %O 打印 JavaScript 对象,可以是整数、字符串或是 JSON 数据。Clicking the object name opens more information about it in the inspector.
%d or %i 打印整数。Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%s 打印字符串。
%f 打印浮点数。Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10

注意:Chrome 不支持精确格式化。

当要替换的参数类型和预期的打印类型不同时,参数会被转换成预期的打印类型。

for (var i=0; i<5; i++) {
  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
}

输出样例如下所示:

[13:14:13.481] Hello, Bob. You've called me 1 times.
[13:14:13.483] Hello, Bob. You've called me 2 times.
[13:14:13.485] Hello, Bob. You've called me 3 times.
[13:14:13.487] Hello, Bob. You've called me 4 times.
[13:14:13.488] Hello, Bob. You've called me 5 times.

为控制台定义样式

你可以使用 %c 为打印内容定义样式:

console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

Using groups in the console

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.

To exit the current group, simply call console.groupEnd(). For example, given this code:

console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.debug("Back to the outer level");

执行结果:

nesting.png

定时器

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

For example, given this code:

console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff...");
console.timeEnd("answer time");

Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:

timerresult.png

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.

堆栈跟踪

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call console.trace(). Given code like this:

function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();

控制台的输出:

规范

规范 状态 备注
Console API Living Standard Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
ConsoleChrome Full support 4Edge Full support YesFirefox Full support 2IE Partial support 8
Notes
Partial support 8
Notes
Notes Only functions when developer tools are opened. Otherwise, the 'console' object is undefined.
Opera Full support 10.1Safari Full support 3.1WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS Full support 3.2Samsung Internet Android Full support Yes
assertChrome Full support YesEdge Full support 12Firefox Full support 28IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 28Opera Android ? Safari iOS ? Samsung Internet Android ?
clearChrome Full support YesEdge Full support 12Firefox Full support 48IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 48Opera Android ? Safari iOS ? Samsung Internet Android ?
countChrome Full support YesEdge Full support 12Firefox Full support 30IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 30Opera Android ? Safari iOS ? Samsung Internet Android ?
countResetChrome Full support YesEdge ? Firefox Full support 62IE No support NoOpera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 62Opera Android ? Safari iOS ? Samsung Internet Android Full support Yes
debugChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support YesOpera ? Safari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
dir
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support 8IE Full support 9Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 8Opera Android ? Safari iOS ? Samsung Internet Android ?
dirxml
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android No support NoOpera Android ? Safari iOS ? Samsung Internet Android ?
errorChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
exception (an alias for error)
DeprecatedNon-standard
Chrome No support NoEdge Full support 13Firefox Full support 28IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android Full support 28Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
groupChrome Full support 4Edge Full support 12Firefox Full support 4IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
groupCollapsedChrome Full support 6Edge Full support 12Firefox Full support 52IE Full support 11Opera ? Safari Full support 5.1WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 52Opera Android ? Safari iOS ? Samsung Internet Android ?
groupEndChrome Full support 4Edge Full support 12Firefox Full support 9IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 9Opera Android ? Safari iOS ? Samsung Internet Android ?
infoChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support Yes
Notes
Full support Yes
Notes
Notes No information icon
WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
logChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
profile
ExperimentalNon-standard
Chrome Full support 53Edge Full support 12Firefox Full support YesIE Full support YesOpera ? Safari ? WebView Android Full support 53Chrome Android Full support 53Firefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
profileEnd
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support YesIE Full support YesOpera ? Safari ? WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
tableChrome Full support YesEdge Full support 13Firefox Full support 34IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 34Opera Android ? Safari iOS ? Samsung Internet Android ?
timeChrome Full support 4Edge Full support 12Firefox Full support 10IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
timeEndChrome Full support 4Edge Full support 12Firefox Full support 10IE Full support 11Opera Full support YesSafari Full support 4WebView Android Full support 37Chrome Android Full support 18Firefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
timeLogChrome Full support 72Edge No support NoFirefox Full support 62IE No support NoOpera Full support 60Safari No support No
Notes
No support No
Notes
Notes See bug 186833.
WebView Android Full support 72Chrome Android Full support 72Firefox Android Full support 62Opera Android ? Safari iOS No support NoSamsung Internet Android No support No
timestamp
ExperimentalNon-standard
Chrome Full support YesEdge Full support 12Firefox Full support YesIE Full support 11Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
traceChrome Full support YesEdge Full support 12Firefox Full support 10IE Full support 11Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 10Opera Android ? Safari iOS ? Samsung Internet Android ?
warnChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 8Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
Available in workersChrome Full support YesEdge Full support YesFirefox Full support 38IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 38Opera Android ? Safari iOS ? Samsung Internet Android ?

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
Compatibility unknown  
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation notes.

注意

  • 在 Firefox 浏览器中,如果页面中自己定义了 console 对象,那么它会覆盖掉浏览器内置的 console 对象,在其它浏览器可能也是。
  • Gecko 12.0 之前的版本中,console 对象中的方法仅在控制台打开的情况下才会执行。Gecko 12.0 之后,控制台未打开时要打印的内容会被缓存,打开控制台时就会把它们全部打印出来。
  • 值得注意的是,Firefox 内置的 Console 对象与 Firebug 插件中的是相互兼容的。

相关文档

  • Tools
  • Web Console - Firefox 浏览器控制台如何处理 console API 的调用
  • Remote debugging - 如何在调试移动设备时查看控制台输出。

其他实现