JavaScript 控制台 API 一览

JavaScript 控制台是一个无价的工具来帮助开发和调试我们的应用程序. 使用控制台对象和其日记方法,呼叫 alert()来调试和获取变量值的日子很长。

落地

console.log 是我们使用的常见方法来将值登录到控制台:

1const name = 'Alligator';
2console.log('Hello', name); // Hello Alligator

但我们还可以访问更多的日志方法,如警告、信息和错误:

1console.info('Just FYI');
2console.warn('Lookout!');
3console.error('Boom 💣');

正如您可以从结果的控制台输出中看到的,使用警告或错误方法也为我们提供了堆栈痕迹:

Logging outputs

您还可以使用「console.trace」启动堆栈跟踪:

1function hello(name = 'Alligator') {
2  console.trace('name:', name);
3  return `Hello ${name}!`;
4}
5
6hello();

...哦,还有console.debug,但它目前只是console.log的代名词。

console.dir 和 console.dirxml 相同

「console.dir」以优雅的格式打印对象:

 1const fancyThings = {
 2  car: '🏎️ Ferrari',
 3  watch: '⌚ Cartier',
 4  clothing: {
 5    shoes: '👠 Christian Louboutin',
 6    dress: '👗 Versace'
 7  },
 8  boat: '🛥️ Sunseeker'
 9}
10
11console.dir(fancyThings);

Output of console.dir


至于「console.dirxml」,它会打印 DOM 元素的标记,例如:

 1<!DOCTYPE html>
 2<html lang="en">
 3
 4<head>
 5  <!-- ... -->
 6</head>
 7
 8<body>
 9  <h1>hello</h1>
10
11  <script>
12    console.dirxml(document.body);
13  </script>
14</body>
15
16</html>

这将产生如下:

Output of console.dirxml

<$>[注意] 如果您感到如此倾斜,您甚至可以使用 console.table以表格格式更清晰地显示控制台中的数据。

主张

「console.assert」方法是运行简单的声明测试的一个简单方法,如果第 1 个参数被评估为 false,则声明会失败,如果声明失败,则将下列参数打印到控制台:

1// this will pass, nothing will be logged
2console.assert(2 == '2', '2 not == to "2"');
3
4// this fails, '3 not === to "3"' will be logged
5console.assert(3 === '3', '3 not === to "3"');

清理

您可以用「console.clear」清除控制台:

1console.clear();

计数

使用「console.count」方法来计算用相同提供的标签被召唤的次数. 例如,这里有两个计数器,一个用于平等值,一个用于奇异值:

 1[1, 2, 3, 4, 5].forEach(nb => {
 2  if (nb % 2 === 0) {
 3    console.count('even');
 4  } else {
 5    console.count('odd');
 6  }
 7});
 8
 9// odd: 1
10// even: 1
11// odd: 2
12// even: 2
13// odd: 3

时机

正如我们在 这篇简短文章中所示,您可以从console.time开始计时器,然后用console.endTime结束计时器。

1console.time('fetching data');
2fetch('https://jsonplaceholder.typicode.com/users')
3  .then(d => d.json())
4  .then(console.log);
5console.timeEnd('fetching data');
6
7// fetching data: 0.2939453125ms
8// (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

<$>[警告] 请注意,如果使用console.time的标签,则必须在调用console.timeEnd时输入相同的标签。

团体

使用console.groupconsole.groupEnd 将主机邮件与可选标签组合。

1console.group('🖍️ colors');
2console.log('red');
3console.log('orange');
4console.group('HEX');
5console.log('#FF4C89');
6console.log('#7186FE');
7console.groupEnd();
8console.log('blue');
9console.groupEnd();

以下是结果的控制台输出:

Output of console.group

奖金:给它一些风格

控制台日志可以用特殊的 %c 划界器进行定型:

1console.log(
2'Hello %cAlligator%c!',
3'color: #008f68; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);',
4'color: hotpink; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);'
5);

在第一个 %c 之后的所有内容都将由第二个参数提供的字符串格式化,然后在下一个 %c 之后的所有内容都将由以下字符串格式化,等等。

Result of styling console output

Published At
Categories with 技术
Tagged with
comments powered by Disqus