zl程序教程

您现在的位置是:首页 >  Java

当前栏目

十个很少人知道的 JavaScript 控制台方法

2023-02-19 12:23:01 时间

您肯定听说过 console.log() 并且可能一直在使用它。它非常流行,像 Visual Studio Intellicode 这样的工具通常会在 IDE 中输入时在任何其他控制台方法之前推荐它:

图片

在今天这篇文章中,我们将探讨一些最有用的控制台方法及其在数据可视化、调试等方面的用途。

1.table()

当您需要直观地查看代码中可以以表格形式表示的一组对象(如对象数组)时,console.table() 方法会派上用场。以这个汽车清单为例:

const cars = [
{
color: 'red',
age: 4,
maxSpeed: 120,
},
{
color: 'blue',
age: 2,
maxSpeed: 100,
},
{
color: 'yellow',
age: 3,
maxSpeed: 160,
},
];

您将如何在控制台中检查它们?console.log() 是一个典型的方法:

console.log(cars);

在 Chrome 开发人员控制台中,我们可以检查我们记录的对象的各种属性,以及我们想要的任意多的层次结构。

我们可以在 Node.js 终端中查看属性并进行着色:

这是一种可接受的方法,但 console.table() 方法提供了一种更优雅的替代方法:

console.table(cars);

顾名思义,它以易于理解的表格格式呈现数据,如电子表格。

table() 也适用于数组数组:

const arr = [
[1, 3, 5],
[2, 4, 6],
[10, 20, 30],
];
console.table(arr);

图片

2. assert()

非常适合调试目的,console.assert() 接受断言并在断言为假时将错误消息写入控制台。但如果这是true,什么也不会发生。

const num = 13;
console.assert(num > 10, 'Number must be greater than 10');
console.assert(num > 20, 'Number must be greater than 20');

第一个断言通过,因为 num 大于 10,所以控制台中只显示第二个:

图片

3. trace()

console.trace() 帮助您在调用它的位置输出当前堆栈跟踪。例如:

function a() {
b();
}
function b() {
c();
}
function c() {
console.trace();
}
a();

4.error()

error() 可能是第二流行的控制台方法。在 Chrome 控制台中,它以独特的红色显示错误消息。

console.error('This is an error message.');
console.log('This is a log message.');

你不会在 Node.js 中获得这种颜色分离:

但是,消息在内部写入不同的位置。console.error() 写入 stderr 流,而 console.log() 写入 stdout 流。您可以使用 process.stderr 和 process.stdout 访问这些流。这对于将错误消息和信息性消息重定向到不同的文件很有用,就像我们在下面的代码示例中所做的那样。

const fs = require('fs');
const errorFs = fs.createWriteStream('./error-log.txt');
process.stderr.write = errorFs.write.bind(errorFs);
const infoFs = fs.createWriteStream('./info-log.txt');
process.stdout.write = infoFs.write.bind(infoFs);
console.error('This is an error message.');
console.log('This is a log message.');

运行此代码时,传递给 error() 和 log() 的消息将输出到相应的文件,而不是控制台。

5.warn()

console.warn() 在 Chrome 控制台中输出一条黄色消息,表示警告。

console.warn('This is a warning message');

图片

在 Node.js 中,消息被写入 stderr 流,如 console.error()。

6. count() 和 countReset()

console.count() 记录当前调用 count() 的次数。另一个有用的调试工具。

function shout(message) {
console.count();
return message.toUpperCase() + '!!!';
}
shout('hey');
shout('hi');
shout('hello');

显示的标签是默认的,因为我们没有指定标签。我们可以通过将字符串参数传递给 count() 来做到这一点。

function shout(message) {
console.count(message);
return message.toUpperCase() + '!!!';
}
shout('hey');
shout('hi');
shout('hello');
shout('hi');
shout('hi');
shout('hello');

图片

现在我们对每条消息都有不同的计数。

countReset() 方法将标签的计数设置回零。

function shout(message) {
console.count(message);
return message.toUpperCase() + '!!!';
}
shout('hi');
shout('hello');
shout('hi');
shout('hi');
shout('hello');
console.countReset('hi');
shout('hi');

7. time()、timeEnd() 和 timeLog()

我们可以一起使用这些方法来测量我们程序中的特定操作需要多长时间。


const arr = [...Array(10)];
const doubles1 = [];
console.time('for of');
let i = 0;
for (; i < 1000; i++) {
for (const item of arr);
}
console.timeLog('for of');
for (; i < 1000000; i++) {
for (const item of arr);
}
console.timeEnd('for of');
console.time('forEach');
i = 0;
for (; i < 1000; i++) {
arr.forEach(() => {});
}
console.timeLog('forEach');
for (; i < 1000000; i++) {
arr.forEach(() => {});
}
console.timeEnd('forEach');

图片

这里我们对 for of 和 forEach 循环进行性能比较。time() 为传递给它的标签指定的操作启动计时器。timeLog() 在不停止计时器的情况下记录当前持续时间,我们用它来显示一千次迭代后经过的时间。timeEnd() 记录当前持续时间并停止计时器。我们在经过一百万次迭代后调用它。

看起来 forEach() 比 for of 快。

8.clear()

console.clear() 通过清除日志来消除控制台的混乱。

console.log('A log message.');
console.clear();

图片

9. group()、groupCollapsed() 和 groupEnd()

console.group() 向其后的任何控制台消息添加一定程度的缩进。console.groupEnd() 将缩进重置为调用前面的 console.group() 之前的级别。

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.log('Back to the outer level');

图片

console.groupCollapsed() 创建一个类似于 console.group() 的组,但是该组会折叠,直到用户使用旁边的显示按钮展开它。

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

图片

10.dir()

console.dir() 的工作方式类似于 console.log(),除了记录 HTMLElements。console.log() 将 HTMLElement 记录为我们可以在控制台中遍历的 HTML:

图片

但是 console.dir() 会将其记录为一个对象,显示一个交互式属性列表:

图片

结论

正如您在本文中看到的,除了 console.log() 之外,还有许多控制台方法。其中一些只是在控制台 UI 中使用颜色和更好的可视化来增添趣味,而另一些则可以作为调试和性能测试的强大工具。

今天内容就先分享到这里,希望对你有用,感谢阅读。