javascript控制台
The JavaScript console is an invaluable tool to help develop and debug our apps. With the console object and its logging methods, long are the days of of calling alert() to debug and get a variable’s value. On top of that, thanks to a work in progress standard, modern browsers are finally supporting the same set of methods. In this post we’ll explore some of the main methods made available by the console API.
JavaScript控制台是帮助开发和调试我们的应用程序的宝贵工具。 使用控制台对象及其日志记录方法,调用alert()调试并获取变量值的日子已经很长了。 最重要的是,由于有一项进行中的工作标准 ,现代浏览器终于支持相同的方法集。 在本文中,我们将探讨控制台API提供的一些主要方法。
记录中 (Logging)
console.log
is the usual method we use to log values out to the console:
console.log
是我们用于将值注销到控制台的常用方法:
const name = 'Alligator';
console.log('Hello', name); // Hello Alligator
But we also have access to more logging methods like warn, info and error:
但是我们也可以访问更多的日志记录方法,例如warn , info和error :
console.info('Just FYI');
console.warn('Lookout!');
console.error('Boom 💣');
As you can see from the resulting console output, using the warn or error methods also gives us a stack trace:
从结果的控制台输出中可以看到,使用warn或error方法还为我们提供了堆栈跟踪:
You can also trigger a stack trace with console.trace
:
您还可以使用console.trace
触发堆栈跟踪:
function hello(name = 'Alligator') {
console.trace('name:', name);
return `Hello ${name}!`;
}
hello();
…Oh, and there’s also console.debug
, but it’s currently just an alias for console.log
.
…哦,还有console.debug
,但是它目前只是console.log
的别名。
console.dir和console.dirxml (console.dir & console.dirxml)
console.dir
prints out objects in a nice formatted way:
console.dir
以一种很好的格式化方式打印出对象:
const fancyThings = {
car: '🏎️ Ferrari',
watch: '⌚ Cartier',
clothing: {
shoes: '👠 Christian Louboutin',
dress: '👗 Versace'
},
boat: '🛥️ Sunseeker'
}
console.dir(fancyThings);
As for console.dirxml
, it prints out a DOM element’s markup. For example:
至于console.dirxml
,它会打印出DOM元素的标记。 例如:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<h1>hello</h1>
<script>
console.dirxml(document.body);
</script>
</body>
</html>
This will output the following:
这将输出以下内容:
If you feel so inclined, you can even display data in the console more neatly in a table format using console.table.
如果您愿意,可以使用console.table以表格格式在控制台中更整洁地显示数据。
断言 (Asserting)
The console.assert
method is an easy way to run simple assertion tests. The assertion fails if the 1st argument evaluates to false, and the subsequent arguments get printed to the console if the assertion fails:
console.assert
方法是运行简单的断言测试的简便方法。 如果第一个参数的计算结果为false,则断言失败,如果断言失败,则后续参数将输出到控制台:
// this will pass, nothing will be logged
console.assert(2 == '2', '2 not == to "2"');
// this fails, '3 not === to "3"' will be logged
console.assert(3 === '3', '3 not === to "3"');
清算 (Clearing)
You can clear the console with console.clear
:
您可以使用console.clear
清除控制台:
console.clear();
数数 (Counting)
The console.count
method is used to count the number of times it has been invoked with the same provided label. For example, here we have two counters, one for even values and one for odd values:
console.count
方法用于计算使用提供的相同标签进行调用的次数。 例如,这里有两个计数器,一个用于偶数,一个用于奇数:
[1, 2, 3, 4, 5].forEach(nb => {
if (nb % 2 === 0) {
console.count('even');
} else {
console.count('odd');
}
});
// odd: 1
// even: 1
// odd: 2
// even: 2
// odd: 3
定时 (Timing)
As we’ve showed in this short post, you can start a timer with console.time
and then end it with console.endTime
. Optionally the time can have a label:
正如我们在这篇简短的文章中所展示的 ,您可以使用console.time
启动一个计时器,然后使用console.endTime
结束它。 时间可以选择带有标签:
console.time('fetching data');
fetch('https://jsonplaceholder.typicode.com/users')
.then(d => d.json())
.then(console.log);
console.timeEnd('fetching data');
// fetching data: 0.2939453125ms
// (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Note that if you use a label with console.time
you must pass-in that same label when calling console.timeEnd
.
请注意,如果在console.time
使用标签,则在调用console.timeEnd
时必须传递相同的标签。
分组 (Grouping)
Use console.group
and console.groupEnd
to group console messages together with an optional label. Notice also how a group can be nested into another one:
使用console.group
和console.groupEnd
将控制台消息与可选标签一起分组。 还请注意如何将一个组嵌套到另一个组中:
console.group('🖍️ colors');
console.log('red');
console.log('orange');
console.group('HEX');
console.log('#FF4C89');
console.log('#7186FE');
console.groupEnd();
console.log('blue');
console.groupEnd();
Here’s the resulting console output:
这是结果控制台输出:
奖励:给予某种风格 (Bonus: Giving it Some Style)
Console logging can be styled using a special %c delimiter:
控制台日志可以使用特殊的%c分隔符设置样式:
console.log(
'Hello %cAlligator%c!',
'color: #008f68; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);',
'color: hotpink; font-weight: bold; font-size: 2rem; text-shadow: 0 0 5px rgba(0,0,0,0.2);'
);
Everything that comes after the first %c will be styled by the string provided by the second argument, then everything after the next %c is styled by the following string argument, and so on. Here’s how the above example looks like at the console:
在第一个%c之后的所有内容都将由第二个参数提供的字符串设置样式,然后在下一个%c之后的所有内容将由以下字符串参数设置样式,依此类推。 这是上面的示例在控制台上的外观:
翻译自: https://www.digitalocean.com/community/tutorials/js-console
javascript控制台