JS控制台日志输出,别再只会 console.log 了(二)

本文已参与「新人创作礼」活动,一起开启掘金创作之路

#

控制台日志输出,别再只会 console.log 了,其实Console 对象还提供了很多简单实用的方法,下面我们就来看看这些方法。

console.assert()

console.assert()方法接受两个参数,第一个参数是表达式,第二个参数是字符串;

只有当第一个表达式不成立时,才会输出第二个参数,否则输出任何东西;

我们在开发中可以使用console.assert()来保证程序正确性。

console.assert(null === undefined, "判断条件不成立")

image.png

例如:我们在日常开发中会遇到某个接口参数不太稳定的情况(因为种种原因某个参数时有时无),从而导致下面代码报错。这种情况真的是令我们前端苦不堪言,记得这有风险还好,忘了就会害得我们白排查一遍。现在使用console.assert()方法,可以很好的帮我们解决这个问题,直接提示我们xxx未获取到,让我们少走弯路;

``` console.assert(targetId != null, "未获取到 targetId"); xxxx.post('URL',{ id: mainId, targetId: xx.targetId xxx: xxxx, }) .then(res => { xxxxxx })

```

console.trace()

console.trace()方法可以用来打印函数调用的栈信息;

我们在调试程序时,有时会查看函数的调用栈信息,这时我们可以在函数的结尾处加入console.trace()来实现。

function fund(a) { console.trace(); return a; } function funb(a) { return func(a); } function func(a) { return fund(a); } var a = funb('666');

image.png

console.group()、console.groupEnd()

*console.group()、console.groupEnd()联合使用,可以将输出的信息分组并支持信息的折叠和展开。 *

我们在日常开发中,有需要分组输出日志信息的可以使用console.group()、groupEnd()方法。

``` console.group('0'); console.log('0-0'); console.log('0-1'); console.groupEnd();

console.group('1'); console.log('1-0'); console.log('1-1'); console.groupEnd(); ```

image.png

console.table()

console.table()方法接收一个强制的参数object,并将object以表格的格式打印输出到控制台;

我非常喜欢使用这个方法,它可以接受数组、对象(JSON)并以表格格式打印简单实用,效果直观。

console.table()传入数组;

console.table(["000", "111", "666"]);

image.png

console.table()传入对象;

console.table({ name : "张三", age : "25" });

image.png

console.table()传入JSON;

``` console.table({

"id":"8fe524b6bb404c30",

"key":"xxxxxxx",

}); ```

image.png

输出样式

Console 对象的方法可以使用%c指令添加样式,出现在%c后的字符串将使用参数中样式;

单次使用%c

console.log("%cMy message", "color: yellow; background-color: blue;padding: 2px");

image.png

多次使用%c

console.log("0 %c123 %c456", "color: red", "color: orange", "789");

image.png

代码示例

``` console.assert(null === undefined, "判断条件%c不成立", "color: yellow; background-color: blue;padding: 2px"); console.group('%c0', "color: yellow; background-color: blue;padding: 2px"); console.log('0-%c0', "color: yellow; background-color: blue;padding: 2px"); console.log('0-%c1', "color: yellow; background-color: blue;padding: 2px"); console.groupEnd();

console.group('%c1', "color: yellow; background-color: blue;padding: 2px");
         console.log('1-%c0', "color: yellow; background-color: blue;padding: 2px");
         console.log('1-%c1', "color: yellow; background-color: blue;padding: 2px");
     console.groupEnd();

```

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱划水de鲸鱼哥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值