javascript控制臺
by Darryl Pargeter
達里爾·帕格特(Darryl Pargeter)
如何充分利用JavaScript控制臺 (How to get the most out of the JavaScript console)
One of the most basic debugging tools in JavaScript is console.log()
. The console
comes with several other useful methods that can add to a developer’s debugging toolkit.
JavaScript中最基本的調試工具之一是console.log()
。 該console
附帶了其他一些有用的方法,這些方法可以添加到開發人員的調試工具箱中。
You can use the console
to perform some of the following tasks:
您可以使用console
執行以下一些任務:
- Output a timer to help with simple benchmarking 輸出計時器以幫助進行簡單基準測試
- Output a table to display an array or object in an easy-to-read format 輸出表以易于閱讀的格式顯示數組或對象
- Apply color and other styling options to the output with CSS 使用CSS將顏色和其他樣式選項應用于輸出
控制臺對象 (The Console Object)
The console
object gives you access to the browser’s console. It lets you output strings, arrays, and objects that help debug your code. The console
is part of the window
object, and is supplied by the Browser Object Model (BOM).
console
對象使您可以訪問瀏覽器的控制臺。 它使您可以輸出有助于調試代碼的字符串,數組和對象。 console
是window
對象的一部分,由瀏覽器對象模型(BOM)提供 。
We can get access to the console
in one of two ways:
我們可以通過以下兩種方式之一來訪問console
:
window.console.log('This works')
window.console.log('This works')
console.log('So does this')
console.log('So does this')
The second option is basically a reference to the former, so we’ll use the latter to save keystrokes.
第二個選項基本上是對前者的引用,因此我們將使用后者來保存擊鍵。
One quick note about the BOM: it does not have a set standard, so each browser implements it in slightly different ways. I tested all of my examples in both Chrome and Firefox, but your output may appear differently depending on your browser.
關于BOM的簡要說明:它沒有設定的標準,因此每個瀏覽器以略有不同的方式實現它。 我在Chrome和Firefox中都測試了所有示例,但是輸出結果可能會因瀏覽器而有所不同。
輸出文字 (Outputting text)
The most common element of the console
object is console.log
. For most scenarios, you’ll use it to get the job done.
console
對象最常見的元素是console.log
。 對于大多數情況,您將使用它來完成工作。
There are four different ways of outputting a message to the console:
有四種將消息輸出到控制臺的方式:
log
log
info
info
warn
warn
error
error
All four work the same way. All you do is pass one or more arguments to the selected method. It then displays a different icon to indicate its logging level. In the examples below, you can see the difference between an info-level log and a warning/error-level log.
所有四個工作方式相同。 您要做的就是將一個或多個參數傳遞給所選方法。 然后,它顯示一個不同的圖標來指示其日志記錄級別。 在下面的示例中,您可以看到信息級日志和警告/錯誤級日志之間的區別。
You may have noticed the error log message - it’s more showy than the others. It displays both a red background and a stack trace, where info
and warn
do not. Though warn
does have a yellow background in Chrome.
您可能已經注意到了錯誤日志消息-它比其他消息更加精美。 它顯示紅色背景和堆棧跟蹤 ,而info
和warn
不顯示。 雖然warn
確實在Chrome中顯示了黃色背景。
These visual differences help when you need to identify any errors or warnings in the console at a quick glance. You would want to make sure that they are removed for production-ready apps, unless they are there to warn other developers that they are doing something wrong with your code.
這些視覺上的差異有助于您快速識別控制臺中的任何錯誤或警告。 您可能要確保將它們刪除以用于生產就緒型應用程序,除非它們在那里警告其他開發人員它們對您的代碼有誤。
字符串替換 (String Substitutions)
This technique uses a placeholder in a string that is replaced by the other argument(s) you pass to the method. For example:
此技術在字符串中使用占位符,該占位符由傳遞給該方法的其他參數替換。 例如:
Input: console.log('string %s', 'substitutions')
輸入 : console.log('string %s', 'substitutions')
Output: string substitutions
輸出 : string substitutions
The %s
is the placeholder for the second argument 'substitutions'
that comes after the comma. Any strings, integers, or arrays will be converted to a string and will replace the %s
. If you pass an object, it will display [object Object]
.
%s
是逗號后第二個參數'substitutions'
的占位符。 任何字符串,整數或數組都將轉換為字符串,并替換%s
。 如果傳遞對象,它將顯示[object Object]
。
If you want to pass an object, you need to use %o
or %O
instead of %s
.
如果要傳遞對象,則需要使用%o
或%O
代替%s
。
console.log('this is an object %o', { obj: { obj2: 'hello' }})
console.log('this is an object %o', { obj: { obj2: 'hello' }})
號碼 (Numbers)
String substitution can be used with integers and floating-point values by using:
可以通過以下方式將字符串替換與整數和浮點值一起使用:
%i
or%d
for integers,%i
或%d
代表整數),%f
for floating-points.%f
為浮點數。
Input: console.log('int: %d, floating-point: %f', 1, 1.5)
輸入 : console.log('int: %d, floating-point: %f', 1, 1.5)
Output: int: 1, floating-point: 1.500000
輸出 : int: 1, floating-point: 1.500000
Floats can be formatted to display only one digit after the decimal point by using %.1f
. You can do %.nf
to display n amount of digits after the decimal.
使用%.1f
可以將浮點數格式化為僅顯示小數點后一位。 您可以執行%.nf
以在小數點后顯示n位數字。
If we formatted the above example to display one digit after the decimal point for the floating-point number, it would look like this:
如果將上面的示例格式化為浮點數的小數點后一位顯示,則如下所示:
Input: console.log('int: %d, floating-point: %.1f', 1, 1.5)
輸入 : console.log('int: %d, floating-point: %.1f', 1, 1.5)
Output:int: 1, floating-point: 1.5
輸出 : int: 1, floating-point: 1.5
格式化說明符 (Formatting specifiers)
%s
| replaces an element with a string%s
| 用字符串替換元素%(d|i)
| replaces an element with an integer%(d|i)
| 用整數替換元素%f
| replaces an element with a float%f
| 用浮點數替換元素%(o|O)
| element is displayed as an object.%(o|O)
| 元素顯示為一個對象。%c
| Applies the provided CSS%c
| 應用提供CSS
字符串模板 (String Templates)
With the advent of ES6, template literals are an alternative to substitutions or concatenation. They use backticks (``) instead of quotation marks, and variables go inside ${}
:
隨著ES6的到來,模板文字可以替代或串聯。 他們使用反引號(``)而不是引號,并且變量放在${}
:
const a = 'substitutions';
console.log(`bear: ${a}`);
// bear: substitutions
Objects display as [object Object]
in template literals, so you’ll need to use substitution with %o
or %O
to see the details, or log it separately by itself.
對象在模板文字中顯示為[object Object]
,因此您需要使用%o
或%O
替換來查看詳細信息,或單獨記錄它們。
Using substitutions or templates creates code that’s easier to read compared to using string concatenation: console.log('hello' + str + '!');
.
與使用字符串連接相比,使用替換或模板創建的代碼更易于閱讀: console.log('hello' + str + '!');
。
漂亮的色彩插曲! (Pretty color interlude!)
Now it is time for something a bit more fun and colorful!
現在該換一些更有趣,更豐富多彩的東西了!
It is time to make our console
pop with different colors with string substitutions.
現在是時候讓我們的console
以字符串替換的不同顏色彈出。
I will be using a mocked Ajax example that give us both a success (in green) and failure (in red) to display. Here’s the output and code:
我將使用一個模擬的Ajax示例,該示例使我們能夠成功顯示(綠色)和失敗(紅色)。 這是輸出和代碼:
const success = [ 'background: green', 'color: white', 'display: block', 'text-align: center'].join(';');
const failure = [ 'background: red', 'color: white', 'display: block', 'text-align: center'].join(';');
console.info('%c /dancing/bears was Successful!', success);console.log({data: { name: 'Bob', age: 'unknown'}}); // "mocked" data response
console.error('%c /dancing/bats failed!', failure);console.log('/dancing/bats Does not exist');
You apply CSS rules in the string substitution with the %c
placeholder.
您可以使用%c
占位符在字符串替換中應用CSS規則。
console.error('%c /dancing/bats failed!', failure);
Then place your CSS elements as a string argument and you can have CSS-styled logs. You can add more than one %c
into the string as well.
然后將CSS元素作為字符串參數放置,您將擁有CSS樣式的日志。 您也可以在字符串中添加多個%c
。
console.log('%cred %cblue %cwhite','color:red;','color:blue;', 'color: white;')
This will output the words ‘red’, ‘blue’ and ‘white’ in their respected colors.
這將以受尊重的顏色輸出單詞“紅色”,“藍色”和“白色”。
There are quite a few CSS properties supported by the console. I would recommend experimenting to see what works and what doesn’t. Again, your results may vary depending on your browser.
控制臺支持很多CSS屬性。 我建議您嘗試一下,看看有什么用,什么沒用。 同樣,您的結果可能會因瀏覽器而異。
其他可用方法 (Other available methods)
Here are a few other available console
methods. Note that some items below have not had their APIs standardized, so there may be incompatibilities between the browsers. The examples were created with Firefox 51.0.1.
這是其他一些可用的console
方法。 請注意,以下某些項目的API尚未標準化,因此瀏覽器之間可能存在不兼容性。 這些示例是使用Firefox 51.0.1創建的。
斷言() (Assert())
Assert
takes two arguments — if the first argument evaluates to a falsy value, then it displays the second argument.
Assert
有兩個參數-如果第一個參數的計算結果為假值,則顯示第二個參數。
let isTrue = false;
console.assert(isTrue, 'This will display');
isTrue = true;
console.assert(isTrue, 'This will not');
If the assertion is false, it outputs to the console. It’s displayed as an error-level log as mentioned above, giving you both a red error message and a stack trace.
如果斷言為假,則輸出到控制臺。 如上所述,它顯示為錯誤級別的日志,同時為您提供紅色錯誤消息和堆棧跟蹤。
Dir() (Dir())
The dir
method displays an interactive list of the object passed to it.
dir
方法顯示傳遞給它的對象的交互式列表。
console.dir(document.body);
Ultimately, dir
only saves one or two clicks. If you need to inspect an object from an API response, then displaying it in this structured way can save you some time.
最終, dir
僅保存一兩次單擊。 如果您需要從API響應中檢查對象,則以這種結構化的方式顯示該對象可以節省一些時間。
表() (Table())
The table
method displays an array or object as a table.
table
方法將數組或對象顯示為表。
console.table(['Javascript', 'PHP', 'Perl', 'C++']);
The array’s indices or object property names come under the left-hand index column. Then the values are displayed in the right-hand column.
數組的索引或對象屬性名稱位于左側索引列下方。 然后,這些值將顯示在右側列中。
const superhero = { firstname: 'Peter', lastname: 'Parker',}console.table(superhero);
Note for Chrome users: This was brought to my attention by a co-worker but the above examples of the table
method don’t seem to work in Chrome. You can work around this issue by placing any items into an array of arrays or an array of objects:
Chrome用戶注意事項:一位同事引起了我的注意,但是以上table
方法示例在Chrome中似乎不起作用。 您可以通過將任何項目放入數組數組或對象數組來解決此問題:
console.table([['Javascript', 'PHP', 'Perl', 'C++']]);
const superhero = { firstname: 'Peter', lastname: 'Parker',}console.table([superhero]);
組() (Group())
console.group()
is made up of at least a minimum of three console
calls, and is probably the method that requires the most typing to use. But it’s also one of the most useful (especially for developers using Redux Logger).
console.group()
至少由至少三個console
調用組成,并且可能是需要使用最多鍵入內容的方法。 但這也是最有用的工具之一(特別是對于使用Redux Logger的開發人員)。
A somewhat basic call looks like this:
一個基本的調用如下所示:
console.group();console.log('I will output');console.group();console.log('more indents')console.groupEnd();console.log('ohh look a bear');console.groupEnd();
This will output multiple levels and will display differently depending on your browser.
這將輸出多個級別,并且將根據您的瀏覽器顯示不同的內容。
Firefox shows an indented list:
Firefox顯示縮進列表:
Chrome shows them in the style of an object:
Chrome以對象的樣式顯示它們:
Each call to console.group()
will start a new group, or create a new level if it’s called inside a group. Each time you call console.groupEnd()
it will end the current group or level and move back up one level.
每次對console.group()
調用都會啟動一個新的組,或者如果在組內調用了新的關卡。 每次調用console.groupEnd()
,它將結束當前組或級別并返回上一級。
I find the Chrome output style is easier to read since it looks more like a collapsible object.
我發現Chrome輸出樣式更易于閱讀,因為它看起來更像一個可折疊的對象。
You can pass group
a header argument that will be displayed over console.group
:
您可以向group
傳遞一個標題參數,該參數將顯示在console.group
:
console.group('Header');
You can display the group as collapsed from the outset if you call console.groupCollapsed()
. Based on my experience, this seems to work only in Chrome.
如果調用console.groupCollapsed()
則可以從一開始就將組顯示為折疊狀態。 根據我的經驗,這似乎僅在Chrome中有效。
時間() (Time())
The time
method, like the group
method above, comes in two parts.
與上面的group
方法一樣, time
方法分為兩個部分。
A method to start the timer and a method to end it.
一種啟動計時器的方法和一種終止計時器的方法。
Once the timer has finished, it will output the total runtime in milliseconds.
計時器結束后,它將以毫秒為單位輸出總運行時間。
To start the timer, you use console.time('id for timer')
and to end the timer you use console.timeEnd('id for timer')
. You can have up to 10,000 timers running simultaneously.
要啟動計時器,請使用console.time('id for timer')
,要結束計時器,請使用console.timeEnd('id for timer')
。 您最多可以同時運行10,000個計時器。
The output will look a bit like this timer: 0.57ms
輸出看起來像這個timer: 0.57ms
It is very useful when you need to do a quick bit of benchmarking.
當您需要快速進行基準測試時,它非常有用。
結論 (Conclusion)
There we have it, a bit of a deeper look into the console object and some of the other methods that come with it. These methods are great tools to have available when you need to debug code.
我們有了它,對控制臺對象及其附帶的其他一些方法有了更深入的了解。 這些方法是需要調試代碼時可用的出色工具。
There are a couple of methods that I have not talked about as their API is still changing. You can read more about them or the console in general on the MDN Web API page and its living spec page.
由于它們的API仍在更改,因此我沒有談論過幾種方法。 您可以在MDN Web API頁面及其實時規格頁面上了解有關它們或控制臺的更多信息。
翻譯自: https://www.freecodecamp.org/news/how-to-get-the-most-out-of-the-javascript-console-b57ca9db3e6d/
javascript控制臺