类似 `console.log` 但更好

2025-05-25

类似 `console.log` 但更好

谁没有在代码中插入 console.log 来查找那些烦人的 bug?这些日志可能令人望而生畏,令人困惑。这些日志将帮助你提升控制台调试体验。

你知道控制台比日志有更多属性吗?自己试试吧!把这些写到你的控制台里,你会感到惊讶的。

console.log(console);
Enter fullscreen mode Exit fullscreen mode

我将介绍我认为最有用的那些。

控制台.表格();

此方法将您的数组和对象显示在一个整洁的表格中。它接受两个参数:数据和您希望显示的列的名称(以数组形式)(可选)。每个元素或属性都对应表格中的一行。

例子:

const array = [1, 2, 3, 4, 5];
const object = {
  name: "Leira",
  lastName: "Sánchez",
  twitter: "MechEngSanchez",
};

console.log('array: ', array); 
// array:  [ 1, 2, 3, 4, 5 ]

console.log('object: ', object); 
// object:  { name: 'Leira', lastName: 'Sánchez', twitter: 'MechEngSanchez' }
Enter fullscreen mode Exit fullscreen mode

使用表格显示的内容更加有条理且易于理解。

console.table(array);
Enter fullscreen mode Exit fullscreen mode

控制台.表(数组)

console.table(object);
Enter fullscreen mode Exit fullscreen mode

console.table(对象)

console.count()

此方法会记录其被调用的次数。我主要用它来检查函数是否按预期被调用。您可以传入一个字符串作为参数,它将作为标签。如果留空,则默认标签为“default”。

let dev = '';
const followMe = (dev) => {
    console.count('followers');
    return `${dev} is following you`;
}

followMe('John'); // followers: 1
followMe('Karen'); // followers: 2
followMe('Camila'); // followers: 3
Enter fullscreen mode Exit fullscreen mode

控制台.assert()

此方法仅在断言为假时才会写入控制台。如果断言为真,则不会显示任何内容。第一个参数是要进行检查的对象。第二个参数是您希望显示的错误消息。

const sum = (n1, n2) => {
    console.assert(n1 + n2 === 10, 'Not 10');
};

sum(3,2); // Assertion failed: Not 10
sum(5,5); //
sum(10,0); //
Enter fullscreen mode Exit fullscreen mode

风格console.log

标签

整理和跟踪 console.log 的一个快速简便的方法是添加标签。只需添加一个字符串作为第一个参数,然后将要记录的内容作为第二个参数即可。为了便于阅读,我还喜欢添加一个冒号和一个空格。

const firstName = 'Leira';
console.log('First Name: ', firstName); // First Name: Leira
Enter fullscreen mode Exit fullscreen mode

您可以添加一个字符串作为其他每个参数,以将多个标签添加到多个值,但我发现这很快就会变得混乱。

const lastName = 'Sánchez';

console.log('First Name: ', firstName, 'Last Name: ', lastName);
// First Name: Leira Last Name: Sánchez
Enter fullscreen mode Exit fullscreen mode

很乱吧?

使用 CSS 添加 Flair!

让你的日志色彩缤纷、美观大方。只需在字符串前面添加“%c”作为第一个参数即可。第二个参数将是 CSS 样式的字符串。

console.log("%cCLICKED!", "font-family:arial;color:green;font-weight:bold;font-size:3rem");
Enter fullscreen mode Exit fullscreen mode

点击

请在评论中告诉我您还如何使用这些方法或您发现哪些其他有用的方法!

文章来源:https://dev.to/leirasanchez/like-console-log-but-better-nhm
PREV
Web 开发者的实用工具
NEXT
为什么在身份验证方面 Cookie 比 localStorage 更可取