Home Web Front-end JS Tutorial JavaScript debugging tips you may not know

JavaScript debugging tips you may not know

Nov 18, 2017 am 09:20 AM
javascript js

If you use a kind of code, you must first understand your tool. Once you are familiar with it, it can greatly help you complete the task. This article tells you some JavaScript debugging skills that you may not know. Although debugging JavaScript is very troublesome, you can still solve it in as little time as possible if you master the tricks. These are errors and bugs. I hope you can master JavaScript debugging skills that you may not know. Take one step further on our journey to accumulate code.


We will list 14 Debugging Tips that you may not know, but once you know it, you will be eager to debug next time Use them when writing JavaScript code!


Start now.


Most of the tips are for Chrome Inspector and Firefox, although many of the techniques can be used with other inspection tools as well.


1. 'debugger;'


'debugger' is my favorite debugger after console.log Tools, simple violence. Just write it into the code and Chrome will automatically stop there when it runs. You can even wrap it with a conditional statement so that it is executed only when needed.

if (thisThing) {
    debugger;
}
Copy after login



2. Output objects into a table


Sometimes you There may be a bunch of objects to look at. You can use console.log to output each object, or you can use the console.table statement to output them directly into a table!

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];
 
console.table(animals);
Copy after login


Output result:

JavaScript debugging tips you may not know



##3. Try all the sizes


#Although it looks cool to put all kinds of mobile phones on the table, it is very uncomfortable. Reality. Why not just resize the interface? Chrome provides everything you need. Go to the Inspector and click the ‘Switch Device Mode’ button so you can resize the window!

JavaScript debugging tips you may not know



4. How to quickly locate DOM elements



Mark a DOM element in the Elements panel and use it in the concole. Chrome Inspector's history saves the last five elements, with the last marked element marked as $0, the second to last marked element marked as $1, and so on.


If you mark the elements in order as 'item-4', 'item-3', 'item-2', 'item-1', 'item-0', you can get the DOM node in the concole:

JavaScript debugging tips you may not know



5. Use console.time() and console.timeEnd() to test loop time


This tool is used when you want to know the execution time of certain code This can be very useful, especially when you are locating time-consuming loops. You can even set multiple timers via tags. The demo is as follows:

console.time('Timer1');
 
var items = [];
 
for(var i = 0; i < 100000; i++){
   items.push({index: i});
}
 
console.timeEnd(&#39;Timer1&#39;);
Copy after login


## Running results:


JavaScript debugging tips you may not know


##6. Get the stack trace information of the function

You probably know that JavaScript frameworks generate a lot of code--quickly.

# It creates views that trigger events and you end up wondering how the function call happened.

#Because JavaScript is not a very structured language, it is sometimes difficult to fully understand what is happening and when. At this time, it’s console.trace’s turn (only trace in the terminal) to debug JavaScript.

Suppose you now want to see the complete stack trace information of the car instance calling the funcZ function on line 33:

var car;
var func1 = function() {
func2();
}
var func2 = function() {
func4();
}
var func3 = function() {
}
var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = ‘volvo’;
this.color = ‘red’;
this.funcX = function() {
this.funcY();
}
this.funcY = function() {
this.funcZ();
}
this.funcZ = function() {
console.trace(‘trace car’)
}
}
func1();
var car; 
var func1 = function() {
func2();
} 
var func2 = function() {
func4();
}
var func3 = function() {
} 
var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = ‘volvo’;
this.color = ‘red’;
this.funcX = function() {
this.funcY();
}
this.funcY = function() {
this.funcZ();
}
 this.funcZ = function() {
console.trace(‘trace car’)
}
} 
func1();
Copy after login

Line 33 will output:

JavaScript debugging tips you may not know


你可以看到func1调用了func2, func2又调用了func4。Func4 创建了Car的实例,然后调用了方法car.funcX,等等。


尽管你感觉你对自己的脚本代码非常了解,这种分析依然是有用的。 比如你想优化你的代码。 获取到堆栈轨迹信息和一个所有相关函数的列表。每一行都是可点击的,你可以在他们中间前后穿梭。 这感觉就像特地为你准备的菜单。


7. 格式化代码使调试 JavaScript 变得容易


有时候你发现产品有一个问题,而 source map 并没有部署到服务器。不要害怕。Chrome 可以格式化 JavaScript 文件,使之易读。格式化出来的代码在可读性上可能不如源代码 —— 但至少你可以观察到发生的错误。点击源代码查看器下面的美化代码按钮 {} 即可。

JavaScript debugging tips you may not know



8. 快速找到调试函数


来看看怎么在函数中设置断点。


通常情况下有两种方法:


1. 在查看器中找到某行代码并在此添加断点
2. 在脚本中添加 debugger


这两种方法都必须在文件中找到需要调试的那一行。


使用控制台是不太常见的方法。在控制台中使用 debug(funcName),代码会在停止在进入这里指定的函数时。


这个操作很快,但它不能用于局部函数或匿名函数。不过如果不是这两种情况下,这可能是调试函数最快的方法。(注意:这里并不是在调用 console.debug 函数)。

var func1 = function() {
func2();
};
 
var Car = function() {
this.funcX = function() {
this.funcY();
}
 
this.funcY = function() {
this.funcZ();
}
}
 
var car = new Car();
Copy after login


在控制台中输入 debug(car.funcY),脚本会在调试模式下,进入 car.funcY 的时候停止运行:

JavaScript debugging tips you may not know



9. 屏蔽不相关代码


如今,经常在应用中引入多个库或框架。其中大多数都经过良好的测试且相对没有缺陷。但是,调试器仍然会进入与此调试任务无关的文件。解决方案是将不需要调试的脚本屏蔽掉。当然这也可以包括你自己的脚本。 点此阅读更多关于调试不相关代码(http://raygun.com/blog/javascript-debugging-with-black-box/)。

JavaScript debugging tips you may not know



10. 在复杂的调试过程中寻找重点


在更复杂的调试中,我们有时需要输出很多行。你可以做的事情就是保持良好的输出结构,使用更多控制台函数,例如 Console.log,console.debug,console.warn,console.info,console.error 等等。然后,你可以在控制台中快速浏览。但有时候,某些JavaScrip调试信息并不是你需要的。


现在,可以自己美化调试信息了。在调试JavaScript时,可以使用CSS并自定义控制台信息:

console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
Copy after login

输出:

JavaScript debugging tips you may not know



例如:


在console.log()中, 可以用%s设置字符串,%i设置数字,%c设置自定义样式等等,还有很多更好的console.log()使用方法。 如果使用的是单页应用框架,可以为视图(view)消息创建一个样式,为模型(models),集合(collections),控制器(controllers)等创建另一个样式。也许还可以像 wlog,clog 和 mlog 一样发挥你的想象力!


11. 查看具体的函数调用和它的参数


在 Chrome 浏览器的控制台(Console)中,你会把你的注意力集中在具体的函数上。每次这个函数被调用,它的值就会被记录下来。


var func1 = function(x, y, z) {

//....

};


然后输出:

JavaScript debugging tips you may not know



This is a great way to see what parameters are passed to a function. But I must say, it would be nice if the console could tell us how many parameters we need. In the above example, function 1 expects 3 parameters, but only 2 parameters are passed in. If the code is not handled in code, it can cause a bug.


12. Quickly access elements in the console


Execute querySelector in the console A faster way is Use the dollar sign. $(‘css-selector’) will return the first matching CSS selector. $$(‘css-selector’) will return all. If you use an element more than once, it deserves to be treated as a variable.

JavaScript debugging tips you may not know



13. Postman is great (but Firefox is faster)


Many developers use Postman to handle Ajax requests. Postman is really good, but every time you need to open a new browser window and write a new request object to test. This is actually a bit annoying.


Sometimes it's easier to just use the browser you're using.


#In this way, if you want to request a password-secured page, you no longer need to worry about verifying the cookie. This is how you edit and resend a request in Firefox.


Open the profiler and go to the network page, right-click on the request you want to process, select Edit and Resend. Now you can change it however you want. You can modify the header information or edit the parameters, and then click Resend.


Now I send the same request twice but with different parameters:

JavaScript debugging tips you may not know



14. Interrupt when the node changes


DOM is an interesting thing. Sometimes it changes and you don't know why. However, if you need to debug JavaScript, Chrome can pause processing when DOM elements change. You can even monitor its properties. On the Chrome profiler, right-click an element and select the Break on option to use

JavaScript debugging tips you may not know

The above are some tips on using JS, there are Friends who are doing research together can discuss it together.

Related reading:

The difference between JavaScript and ECMAScript


JavaScript implements drop-down menu Example


24 JavaScript Interview Questions


The above is the detailed content of JavaScript debugging tips you may not know. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles