机械秒表的使用方法_让console.log()不再是你的唯一选项js日志输出6种方法
幾乎所有的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()相當于計時結束
// "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
總結
以上是生活随笔為你收集整理的机械秒表的使用方法_让console.log()不再是你的唯一选项js日志输出6种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原生android字体,不用Root,国
- 下一篇: tableview直接滚动至最后一行