幾乎所有的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
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客。
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! 。另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注。