[翻译]你真的会用console.log吗?

对于广大的前端工程师来讲,在浏览器或者程序中通过console.log()来调试输出变量信息是常用的一种方式,你可能了解过console.error()、console.warning(),但总是用于输出文本吧,今天看到一篇比较好的外文,做了适当翻译和修饰,供君阅读和参考。

在浏览器控制台打印输出信息,极大地方便了开发者的调试以及解决问题。console.log() 该方法输出的信息就像是解决难缠问题的一剂良药。而且大多数的开发者都想这样——让我在浏览器控制台获得更多与问题有关的信息。我很确定我并不是唯一这样想的人。

除了通常使用console.log()在浏览器中打印输出信息,还有很多不同的方法使得你的调试过程更加容易。接下来让我们通过示例了解一下它们吧。

0x00 console.log( ) | info( ) | debug( ) | warn( ) | error( )

它们会在浏览器控制台中打印原始的字符串内容,并且根据不同的“等级”,而文字的颜色有所不同。

示例

0x01 使用占位符

Javascript提供了很多占位符,可以用于调试输出的有如下:

  • %o — 对象占位
  • %s — 字符串占位
  • %d — 数字占位

占位符

0x02 给输出的内容添加CSS

你是否会认为所有的console方法输出的区别不大?好吧,从现在开始它将不再相同,使得您更容易找到你所关心的问题

使用%c这个占位符,可以像写行内样式一样,自定义输出内容的样式

css自定义

这样用

0x03 console.dir()

输出指定对象的JSON格式,其实在console.info()这个方法中,会自动判断是否为对象来决定是否打印输出JSON格式。console.dir()强制做了这件事儿。

输出json格式

0x04 格式化输出HTML元素

可以通过js获取到DOM节点,然后打印输出,效果和在开发者工具中的“Elements”选项卡类似,这里的功能就是对HTMLElements做了一个默认的DOM格式化吧。

0x05 console.table()

想要更加直观/美观展示JSON格式的数据?

table

0x06 console.group( ) & console.groupEnd( )

它会尽可能地将打印的信息组织在一起,这样的话,我们的输出看起来就更加的有层次、有组织

分组输出

0x07 console.count( )

count() 用来打印调用次数,一般用在循环或递归函数中。接收一个 label 参数以定制输出,默认直接输出 1 2 3 数字。

0x08 console.assert( )

console 版断言工具,当且仅当第一个参数值为 false 时才打印第二个参数作为输出。

这种输出结果为 error,所以也可被 console.error + 代码级别断言所取代。

0x09 console.trace( )

打印此时的调用栈,在打印辅助调试信息时非常有用。

0x0A console.time( )

打印代码执行时间,性能优化和监控场景比较常见。

0x0B console.memory

打印内存使用情况。

0x0C console.clear( )

清空控制台输出。

0x0D 总结

通过如上的例子,console为我们发现输出控制台信息的提供了很多方式,那么在日志打印和调试输出的时候,是否就可以做一些关于规范话的内容呐?

比如基于console 封装的logger,做一些更加规范化的输出,相信对于团队成员解决问题更加有帮助。

Reference

下面的代码是例子中用到的参考示例的集合:

// time and time end
console.time("This");
let total = 0;
for (let j = 0; j < 10000; j++) {
  total += j
}
console.log("Result", total);
console.timeEnd("This");

// Memory
console.memory()

// Assertion
const errorMsg = 'Hey! The number is not even';
for (let number = 2; number <= 5; number += 1) {
    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
}

// Count
for (let i = 0; i < 11; i++) {
  console.count();
}

// group & groupEnd
console.group();
  console.log('Test message');
  console.group();
    console.log('Another message');
    console.log('Something else');
  console.groupEnd();
console.groupEnd();


// Table
const items = [
  {
    name: "chair",
    inventory: 5,
    unitPrice: 45.99
  },
  {
    name: "table",
    inventory: 10,
    unitPrice: 123.75
  },
  {
    name: "sofa",
    inventory: 2,
    unitPrice: 399.50
  }
];
console.table(items)

// Clear
console.clear()

// HTML Element
let element = document.getElementsByTagName("BODY")[0];
console.log(element)

// Dir
const userInfo = {"name":"John Miller", "id":2522, "theme":"dark"}
console.dir(userInfo);

// Color
console.log('%cColor of the text is green plus small font size', 'color: green; font-size: x-small');

// pass object, variable
const userDetails = {"name":"John Miller", "id":2522, "theme":"dark"}
console.log("Hey %s, here is your details %o in form of object", "John", userDetails);

// Default
console.log('console.log');
console.info('console.info');
console.debug('console.debug');
console.warn('console.warn');
console.error('console.error');
发表评论 / Comment

用心评论~

金玉良言 / Appraise
逍遥游LV 1
2022-01-02 11:05
哈哈 : https://bytedance.feishu.cn/docx/doxcnMMV6bESzcFdrySSNcTz4Dh
腾讯视频LV 2
2021-03-19 17:38
学习
孤独LV 1
2020-10-21 17:06
还能有这么多花样,学习了

Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23