Javascript debugging method: 1. Use the "console.log" method to print the object on the console, the syntax is "console.log(object)"; 2. Use the "console.time" method to print the program execution on the console Time, syntax "console.time('label')".
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
1. Learn to use console.log
Everyone can use console.log, but many students only know the simplest console. .log(x) prints an object like this. When there are too many console.logs in your code, it will be difficult to match a certain print result with the code, so we can add a label to the print information for easy differentiation:
let x = 1;console.log('aaaaaaaa', x);
gets:
The tag does not have to have a clear meaning, as long as the visual effect is significant, of course it is better to have a clear meaning.
In fact, console.log can receive any number of parameters, and finally splice these objects for output, such as:
If there is too much printed information, it will not If the target information is easy to find, you can filter it in the console:
Notes
Print a reference when using console.log When using an object of a certain type (such as arrays and custom objects), the output result may not be the value at the time when the console.log method is executed. For example:
It can be found that the results output by the two console.logs are [1, 2, 3, 4] after expansion. Because the array is a reference type, so After expansion, the latest status of the array is obtained. We can use JSON.parse(JSON.stringify(...)) to solve this problem:
2. Learn to use console.time
Sometimes we want to know the performance of a piece of code or how long an asynchronous method needs to run. At this time, we need to use a timer. JavaScript provides a ready-made console.time method, for example:
Recommended learning: css video tutorial
The above is the detailed content of How to debug javascript. For more information, please follow other related articles on the PHP Chinese website!