前言

控制台日志输出,别再只会 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