- Published on
12-console.log 并不简单
- Authors
- Name
- Dendoink
- @Magiciaaaaaaaan
console.assert
1. 设想你遇到这样的情况:当某个值判断为假(空字符串,undefined 或者 null)的时候,你期望能在 log 中把它打印出来:
一般的写法是这样:

没有任何问题,就是不够优雅,优雅的写法应该是怎样呢:

💡
敲黑板 当我们传入的第一个参数为 时, console.assert
打印跟在这个参数后面的值。
⚠️
请注意 请注意,,但是在 .10
的版本中被修复了(当然,在浏览器中不存在这个问题)
log
的阅读体验
2. 增强 假如有这么一堆看起来并不易读的数据要打印在 console 里面:
const name = "frontend-wingman"
const url = "www.frontendwingman.com"
const chapter = "console"

光看输出的结果,我们很难判断打印的到底是哪个变量,为了让它变得更加易读,你可以打印一个对象:
- 将所有
console.log
的参数包装在大括号中。
console.log({name, url, chapter})
💡
敲黑板 原理就是 ES6
中 ,所以只要加上 {}
就完事儿了:

console.table
3. console.table
这个小技巧在开发者中可能并没有多少人知道:
console.table
可以将 数组 (或者是 类数组 的对象,或者就是一个 对象 )打印成一个漂亮的表格。
它不仅会根据数组中包含的对象的所有属性,去计算出表中的列名,而且这些列都是可以 缩放 甚至 还可以排序!!!
如果你觉得展示的列太多了,使用第二个参数,传入你想要展示的列的名字:

💡
敲黑板 对于后台而言,只有 node
版本大于 10
以上, console.table
才能起作用
Related series
00-写在前面
March 2, 2021
01-Chrome 版本
March 2, 2021
02-复制 & 保存
March 2, 2021
03-快捷键和通用技巧
March 2, 2021
04-使用 Command
March 2, 2021
05-代码块的使用
March 2, 2021
06-console 中的 $
March 2, 2021
07-console.log 的 "bug" ?
March 2, 2021
08-异步的 console
March 2, 2021
09-Ninja console.log
March 2, 2021
10-自定义格式转换器
March 2, 2021
11-对象&方法
March 2, 2021
12-console.log 并不简单
March 2, 2021
13-打造一个终极 log
March 2, 2021
14-打印时间戳
March 2, 2021
15-直接把 `log` 作为回调函数
March 2, 2021
16-初窥 Network
March 2, 2021
17-Network 深入
March 2, 2021
18-Network 细节
March 2, 2021
19-元素面板的基本操作
March 2, 2021
20-元素面板调试技巧
March 2, 2021
21-元素面板里的编辑器
March 2, 2021
22-颜色选择器
March 2, 2021
23-Drawer 使用技巧
March 2, 2021
24-Drawer 动画调试
March 2, 2021
25-Drawer 性能优化
March 2, 2021
26-Workspace 使用技巧
March 2, 2021
27-自动美化输出
March 2, 2021
28-CSS 概览
March 2, 2021
29-Custom UI Themes
March 2, 2021
30-Source diff
March 2, 2021