用法列表
- 正常用法
- 插入值
1
| console.log('Hello I am a %s string!', '💩');
|
%s 是格式化符號(format specifier),意思是「這裡要插入一個字串(string)」,’💩’ 則是要插入的字串
- 加入樣式
1
| console.log('%c I am some great text', 'font-size:50px; background:red; text-shadow: 10px 10px 0 blue')
|
%c 代表要加入樣式,第二個參數則加入 css 樣式
- 警告樣式
1
| console.warn('OH NOOO');
|
- 錯誤樣式
- 提示樣式
1
| console.info('Crocodiles eat 3-4 people per year');
|
- 判斷輸出
條件為 false,會輸出錯誤訊息:
1 2
| let y = -3; console.assert(y > 0, '錯誤:y 不是正數');
|
- 清除 console.log 訊息
- 查看 dom 結構
1 2
| const p = document.querySelector('p'); console.dir(p);
|
- 群組訊息
1 2 3 4 5
| console.groupCollapsed('使用者資訊'); console.log('名稱:心可可'); console.log('年齡:18'); console.log('興趣:寫程式、聽 Ado 歌'); console.groupEnd();
|
console.groupCollapsed() 是一個用來在瀏覽器開發者工具的主控台中建立「可折疊的訊息群組」的方法。
- 計算訊息次數
1 2 3 4 5
| console.count('Wes'); console.count('Wes'); console.count('Steve'); console.count('Steve'); console.count('Wes');
|
會得到
Wes: 1
Wes: 2
Steve: 1
Steve: 2
Wes: 3
- 計算執行花費間
1 2 3 4 5 6 7
| console.time('fetching data'); fetch('https://api.github.com/users/wesbos') .then(data => data.json()) .then(data => { console.timeEnd('fetching data'); console.log(data); });
|