Home > Web Front-end > Front-end Q&A > How to debug javascript

How to debug javascript

醉折花枝作酒筹
Release: 2023-01-05 16:08:18
Original
3435 people have browsed it

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')".

How to debug javascript

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);
Copy after login

gets:

How to debug javascript

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:

How to debug javascript

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:

How to debug javascript

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:

How to debug javascript

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:

How to debug javascript

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:

How to debug javascript

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template