
幾乎所有的javascript開發者最常使用的日志列印除錯api都是console.log(),其實還有很多的選項供我們選擇,筆者下面就為大家一一介紹.
一、console.table()
console.table()是我非常建議大家去使用的方法,它可以接受JSON或陣列并以表格格式列印,在對json物件和陣列進行可視化列印的時候簡單易用,結果直觀,
比如下面的json資料物件使用console.table()列印
console.table({
"id":"1",
"key":"value",
"count":2
});
控制臺的輸出結果如下:

又比如對下面代碼中的陣列進行列印:
console.table([
{
id: "1",
key: "value",
count: 2,
},
{
id: "2",
key: "value2",
count: 22,
},
{
id: "3",
key: "value3",
count: 5,
},
]);
控制臺的輸出結果如下:

二、console.error()
console.error()相對于console.log()更有助于在除錯時從輸出日志中區分錯誤資訊

從上圖中可以看到,它的輸出列印結果是紅色的,
三、Time(time,timeLog,timeEnd)
console.time()、console.timeLog()、console.timeEnd() 這三個方法當我們對程式運行時間進行計時的時候特別有用,
參考下圖理解這三個方法

- console.time()相當于秒表中的開始按鈕
- console.timeLog()相當于秒表中的按圈計時/按點計時
- console.timeEnd()相當于計時結束
console.time("ForLoop");
// "ForLoop" is label here
for (let i = 0; i < 5; i++) {
console.timeLog('ForLoop');
}
console.timeEnd("ForLoop");
控制臺列印輸出結果

四、console.warn()
用黃色字體輸出日志,更直觀的方便的查看警告類日志資訊,

五、console.assert()
console.assert(assert_statement,message)用來設定斷言,如果為false則顯示message訊息
if(3!=2){
console.error({ msg1: "msg1", msg2: "msg2" });
}
//上面的日志判斷陳述句,可以簡寫為下面的斷言
console.assert(3 === 2, { msg1: "msg1", msg2: "msg2" });

另一種可以用來格式化輸出的斷言方式console.assert(assert_statement,message,args)
console.assert(false, "%d nd type for %s ",2,"console.assert() method");

六、console.count()
console.count()特別適合用來計數,可以傳遞引數,可以根據根據引數標簽統計次數,代碼如下:
for (let i = 0; i < 3; i++) {
console.count("label");
console.count();
console.count(i);
}
控制臺列印輸出的結果,類似于下面這樣
console.count() console.count("label") console.count(i)
default: 1 label: 1 0: 1
default: 2 label: 2 1: 1
default: 3 label: 3 2: 1
console.count()如果不傳遞引數,則使用默認的default標簽,console.countReset(標簽引數)可以將指定標簽的計數重置為0
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客,
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! ,另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注,
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前后端分離RBAC權限管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/165776.html
標籤:其他
