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

JavaScript debugging tips you may not know

php中世界最好的语言
Release: 2017-11-18 09:20:10
Original
1382 people have browsed it

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!

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