对 console.log 说不!

2025-05-28

对 console.log 说不!

您在开发过程中是否经常console.log在项目中使用?

尽管我们会继续使用console.log,但还有其他替代方案可以让您的开发更有趣、更高效。

 

注意:如果您在终端中查看日志,尤其是后端开发人员,那么您可以尝试JSON.stringify(your_data, null, 2)使用console.log()结果。这将确保您不会进入{... value: [Object, Object]}日志,并且日志也会被格式化,使其更易于阅读。

 

控制台.dir()

用于数组和对象的层次列表。

console.dir(["apples", "oranges", "bananas"]);
Enter fullscreen mode Exit fullscreen mode

console.dir 示例

 

控制台.table()

对于数组的行和列列表(可能不适合对象)。

console.table(["apples", "oranges", "bananas"]);
Enter fullscreen mode Exit fullscreen mode

console.table 数组示例

console.table({"a": 1, "b": 2, "c": 3});
Enter fullscreen mode Exit fullscreen mode

console.table 对象示例

 

控制台.group()

console.log('This is the top outer level');

console.group('Task 1');
console.log('Task activity 1');
console.log('Task activity 2');
console.groupEnd();

console.group('Task 2');
console.log('Task activity 3');
console.log('Task activity 4');
console.groupEnd();

console.log('Back to the top outer level');

Enter fullscreen mode Exit fullscreen mode

console.group 示例

 

console.time() 和 console.timeEnd()

try {
  console.time("record-1");
  await someAsyncTask();
} catch (error) {
   // handle error
} finally {
  console.timeEnd("record-1");
}
Enter fullscreen mode Exit fullscreen mode

console.time 日志

 

控制台.clear()

这将清除控制台。

 
希望以上内容对您有帮助!🚀

文章来源:https://dev.to/wootcot/say-no-to-consolelog-556n
PREV
面向 2025 年的现代 Node.js + TypeScript 配置
NEXT
2022 年适用于 Python 开发人员的最佳 VS Code 扩展。