As we all know, the developer tools of the browser provide us with a powerful debugging system, which can be used to view DOM tree structure, CSS style debugging, animation debugging, JavaScript code breakpoint debugging, etc. Today, let's take a look at the practical debugging skills of console debugging.
Nowadays, our project development usually uses front-end frameworks such as React and Vue, and front-end debugging becomes more difficult. In addition to using plug-ins such as React Dev Tools and Vue Dev Tools, console.log() is the most used. Of course, console.log() can meet our needs in most cases, but when the data becomes more complex, console.log() It seems a little single. In fact, the console object provides us with many printing methods. The following are the methods contained in the console object (Chrome browser is used here, version 95.0.4638.54 (official version) (arm64)):
The console object provides an interface for browser console debugging. We can access it from any global object. If you only use console.log() to output some variables, you may not have used the powerful functions of console. Let's play fancy debugging with console.
1, Basic printing
1. console.log()
console.log() is the most basic and commonly used usage. It can be used anywhere in JavaScript code, and then the printed information can be seen in the browser console. Its basic usage is as follows:
let name = "CUGGZ"; let age = 18; console.log(name) // CUGGZ console.log(`my name is: ${name}`) // CUGGZ console.log(name, age) // CUGGZ 18 console.log("message:", name, age) // message: CUGGZ 18 Copy code
In addition, console.log() supports the following output modes:
let name = "CUGGZ"; let age = 18; let height = 180; console.log('Name: %s, Age: %d', name, age) // Name: CUGGZ, Age: 18 console.log('Age: %d, Height: %d', age, height) // Age: 18, Height: 180 Copy code
Here, the following variables are assigned to the position of the previous placeholder, and they correspond to each other one by one. This writing method can ensure the separation of template and data and clearer structure in complex output. However, if it is a simple output, there is no need to write it like this. In console.log, the supported placeholder formats are as follows:
- String:% s
- Integer:% d
- Floating point number:% f
- Object:% o or% o
- CSS Style:% c
You can see that in addition to the most basic types, it also supports the definition of CSS styles:
let name = "CUGGZ"; console.log('My Name is %cCUGGZ', 'color: skyblue; font-size: 30px;') Copy code
The printing results are as follows (there seems to be no egg):
Where this style printing may be useful is to print pictures to check whether the pictures are correct:
console.log('%c ','background-image:url("http://iyeslogo.orbrand.com/150902Google/005.gif");background-size:120% 120%;background-repeat:no-repeat;background-position:center center;line-height:60px;padding:30px 120px;'); Copy code
The printing results are as follows:
Strictly speaking, console.log() does not support printing pictures, but you can use the background image of CSS to print pictures, but you can't print directly. Because it doesn't support setting the width and height properties of pictures, you need to use line height and padding to open the pictures so that they can be displayed normally.
We can use console.log() to print character drawings, as we know:
You can use the character drawing online generation tool to paste the generated characters into console.log(). Online tools: mg2txt . The generation effect of my avatar is as follows, and the generated characters are in the middle:
In addition, you can see that when placeholders represent an object, they can be written in two ways:% C or% C. what is the difference between them? When the object we specify is an ordinary object object, there is no difference between them. If it is a DOM node, there is a difference. Take the following example:
As you can see, using%O prints the contents of the DOM node, including its child nodes. And% O prints the object attributes of the DOM node, which can be selectively printed according to needs.
2. console.warn()
The console.warn() method is used to output a warning message on the console. Its usage is exactly the same as that of console.log, except that the display style is different. A yellow triangle is added in front of the information to indicate a warning:
const app = ["facebook", "google", "twitter"]; console.warn(app); Copy code
Plot styles are as follows:
3. console.error()
console.error() can be used to output error messages on the console. Its usage is the same as the above two methods, but the display style is different:
const app = ["facebook", "google", "twitter"]; console.error(app); Copy code
Note that console.exception() is the alias of console.error(), and their functions are the same.
Of course, console.error() has another function that console.log() does not have, that is, printing the function call stack:
function a() { b(); } function b() { console.error("error"); } function c() { a(); } c(); Copy code
The printing results are as follows:
You can see that the function call stack information is printed here: b → a → c.
The console object provides a special method to print the function call stack (console.trace()), which will be introduced below.
4. console.info()
console.info() can be used to print information class description information. Its usage is the same as console.log(), and the printing effect is the same:
2, Print time
1. console.time() & console.timeEnd()
If we want to obtain the execution time of a piece of code, we can use the console.time() and console.timeEnd() methods of the console object to see the following example:
console.time(); setTimeout(() => { console.timeEnd(); }, 1000); // default: 1001.9140625 ms Copy code
They can all pass a parameter, which is a string used to mark a unique timer. If the page has only one timer, you do not need to pass this parameter. If there are multiple timers, you need to use this tag to mark each timer:
console.time("timer1"); console.time("timer2"); setTimeout(() => { console.timeEnd("timer1"); }, 1000); setTimeout(() => { console.timeEnd("timer2"); }, 2000); // timer1: 1004.666259765625 ms // timer2: 2004.654052734375 ms Copy code
2. console.timeLog()
The console.timeLog() here is similar to the console.timeEnd() above, but there are some differences. They all need to use console.time() to start a timer. Then, console.timeLog() is the current time of the print timer, and console.timeEnd() is the time until the end of the print timer. Here are some examples:
console.time("timer"); setTimeout(() => { console.timeLog("timer") setTimeout(() => { console.timeLog("timer"); }, 2000); }, 1000); // timer: 1002.80224609375 ms // timer: 3008.044189453125 ms Copy code
When using console.timeEnd():
console.time("timer"); setTimeout(() => { console.timeEnd("timer") setTimeout(() => { console.timeLog("timer"); }, 2000); }, 1000); Copy code
The printing results are as follows:
As you can see, it will terminate the current timer, so the timer counter cannot be found in the timeLog. So the difference between the two is whether the current timing will be terminated.
3, Group printing
1. console.group() & console.groupEnd()
These two methods are used to create an information group in the console. A complete information grouping starts with console.group() and ends with console.groupEnd(). Consider the following example:
console.group(); console.log('First Group'); console.group(); console.log('Second Group') console.groupEnd(); console.groupEnd(); Copy code
The printing results are as follows:
Let's look at a more complex one:
console.group("Alphabet") console.log("A"); console.log("B"); console.log("C"); console.group("Numbers"); console.log("One"); console.log("Two"); console.groupEnd("Numbers"); console.groupEnd("Alphabet"); Copy code
The printing results are as follows:
As you can see, these groups can be nested. At present, we need to debug a lot of debugging output, so we can choose to use grouped output,
2. console.groupCollapsed()
The console.groupCollapsed() method is similar to console.group(). Both of them need to use console.groupEnd() to end the grouping. The difference is that the information printed by this method is folded and displayed by default, while group() is expanded by default. To rewrite the above example:
console.groupCollapsed("Alphabet") console.log("A"); console.log("B"); console.log("C"); console.groupCollapsed("Numbers"); console.log("One"); console.log("Two"); console.groupEnd("Numbers"); console.groupEnd("Alphabet"); Copy code
The printing results are as follows:
You can see that the only difference from the above method is that the printed results are folded and need to be expanded manually.
4, Print count
1. console.count()
You can use console.count() to get the current number of executions. Consider the following example:
for (i = 0; i < 5; i++) { console.count(); } // The output results are as follows default: 1 default: 2 default: 3 default: 4 default: 5 Copy code
It can also pass a parameter to mark (if it is empty, it is the default label default):
for (i = 0; i < 5; i++) { console.count("hello"); } // The output results are as follows hello: 1 hello: 2 hello: 3 hello: 4 hello: 5 Copy code
This method is mainly used in some complex scenarios. Sometimes a function is called in multiple places, you can use this method to determine whether the method is called less or repeatedly.
2. console.countReset()
As the name suggests, console.countReset() is to reset the calculator, which needs to be used in conjunction with the above console.count() method. It has an optional parameter label:
- If the parameter label is provided, this function resets the count associated with the label and resets the count to 0.
- If the parameter label is omitted, this function resets the default counter and resets the count to 0.
console.count(); console.count("a"); console.count("b"); console.count("a"); console.count("a"); console.count(); console.count(); console.countReset(); console.countReset("a"); console.countReset("b"); console.count(); console.count("a"); console.count("b"); Copy code
The printing results are as follows:
default:1 a:1 b:1 a:2 a:3 default:2 default:3 default:1 a:1 b:1 Copy code
5, Other printing
1. console.table()
We usually use console.log more. In fact, there are many properties of the console object that can be used, such as console.table(). It is convenient to print the properties of the array object, and the print result is a table. The console.table() method has two parameters. The first parameter is the object to be printed, and the second parameter is the title of the table to be printed. Here is the attribute value of the array object. Consider the following example:
const users = [ { "first_name":"Harcourt", "last_name":"Huckerbe", "gender":"Male", "city":"Linchen", "birth_country":"China" }, { "first_name":"Allyn", "last_name":"McEttigen", "gender":"Male", "city":"Ambelókipoi", "birth_country":"Greece" }, { "first_name":"Sandor", "last_name":"Degg", "gender":"Male", "city":"Mthatha", "birth_country":"South Africa" } ] console.table(users, ['first_name', 'last_name', 'city']); Copy code
The printing results are as follows:
In this way, you can more clearly see the specified attributes in the array object.
In addition, you can use console.table() to print array elements:
const app = ["facebook", "google", "twitter"]; console.table(app); Copy code
The printing results are as follows:
In this way, we can see the elements in the array more clearly.
Note that console.table() can only handle up to 1000 rows, so it may not be suitable for all datasets. But it can also be applied to most scenarios.
2. console.clear()
console.clear() as the name suggests is to clear the console information. After the console is cleared, the following message will be printed: "console was cleared":
Of course, we can use the clear key on the console to clear the console:
3. console.assert()
The console.assert() method is used for statement assertion. When the assertion is false, an error message will be output to the console. Its syntax is as follows:
console.assert(expression, message) Copy code
It has two parameters:
- expression: conditional statement. The statement will be parsed into Boolean, and the message statement output will be triggered when it is false;
- message: output statement, which can be any type.
This method will print message when the expression condition statement is false. The console.assert() method can be used when the statement is output only under certain circumstances.
For example, when the number of child nodes of a list element is greater than or equal to 100, an error message is printed:
console.assert(list.childNodes.length < 100, "Node count is > 100"); Copy code
The output results are shown in the figure below:
4. console.trace()
The console.trace() method can be used to print the call path of the currently executing code in the stack. It works the same as console.error() above, but the print style is the same as console.log(). Consider the following example:
function a() { b(); } function b() { console.trace(); } function c() { a(); } c(); Copy code
The printing results are as follows:
You can see that the information of the call stack is output here: b → a → c. This stack information starts from the call position.
5. console.dir()
The console.dir() method can display the properties of the specified JavaScript object in the console and display them through an interactive list similar to the file tree style. Its syntax is as follows:
console.dir(object); Copy code
Its parameter is an object, which will eventually print out all the attributes and attribute values of the object.
In most cases, using consoledir() has the same effect as using console.log(). However, there is a big difference when printing the element structure. console.log() prints the DOM structure of the element, while console.dir() prints the attributes of the element:
6. console.dirxml()
The console.dirxml() method is used to display an interactive tree of explicit XML/HTML elements, including all descendant elements. If it cannot be displayed as an element, it will be replaced in the form of a JavaScript object. Its output is an inherited and extended node list, which allows you to see the contents of child nodes. The syntax is as follows:
console.dirxml(object); Copy code
This method prints out XML elements and their descendants. Calling console.log() and console.dirxml() for XML and HTML elements is equivalent.
7. console.memory
console.memory is a property of the console object, not a method. It can be used to check the current memory usage. If too much console.log() is used, it will occupy more memory and cause the browser to get stuck.
last
If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts
If you think this article is useful to you, please click star: http://github.crmeb.net/u/defu esteem it a favor !