search
HomeWeb Front-endJS TutorialDetailed explanation of more than a dozen practical JavaScript debugging tips with pictures and codes

'debugger;'

In addition to console.log, debugger is another quick debugging tool that I like very much. After the debugger is added to the code, Chrome will automatically stop where it is inserted, much like breakpoints in C or Java. You can also insert this debugging statement in some conditional controls, for example:

if (thisThing) {
    debugger;
}

Display Objects in table form

Sometimes we need to see the detailed information of some complex objects. The simplest The method is to use console.log and then display it in a list, scroll up and down to browse. However, it seems that it would be better to display it as a list using console.table, which probably looks like this:

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];

console.table(animals);

Multiple screen size test

Chrome has a very attractive feature that is able to simulate the sizes of different devices. Click the toggle device mode button in Chrome's Inspector, and then you can debug under different device screen sizes:

Quickly select a DOM element in the Console

It is also a very common operation to select a DOM element in the Elements selection panel and then use the element in the Console. , Chrome Inspector will cache the last 5 DOM elements in its history. You can use methods similar to $0 in Shell to quickly associate to elements. For example, the list below has the elements 'item-4', 'item-3', 'item-2', 'item-1', 'item-0'. You can use it like this:

Get the call tracking record of a certain function

The JavaScript framework greatly facilitates our development, but it also brings a large number of predefined functions, such as creating View , binding events, etc., so that it is not easy for us to track the calling process of our custom functions. Although JavaScript is not a very rigorous language, sometimes it can be difficult to figure out what is going on, especially when you need to review other people's code. At this time console.trace will come into play, it can help you trace function calls. For example, in the following code, we need to trace the calling process of funcZ in the car object:

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();

Here you can clearly see that func1 calls func2, and then calls func4, and func4 creates an instance of Car and then car.funcX is called.

Format compressed code

Sometimes we find some inexplicable problems in the production environment, and then forget to put the sourcemaps on this server, or look at other people's homes When I looked at the source code of the website, I saw a bunch of code that I didn’t know what to say, like the picture below. Chrome provides us with a very user-friendly decompression tool to enhance the readability of the code. It can be used like this:

Quickly locate debugging functions

When we want to add a breakpoint in a function, we usually choose to do this:

  • Find the specified line in the Inspector, and then add a breakpoint

  • Add a debugger call in the script

However, there is a small problem with both methods, that is, you have to go to the corresponding script file and then find the corresponding line, so It will be more troublesome. Here is a relatively quick method, which is to use debug(funcName) in the console and the script will automatically stop at the place where the corresponding function is specified. A flaw of this method is that it cannot stop at a private function or anonymous function, so it still has to vary from time to time:

var func1 = function() {
func2();
};

var Car = function() {
this.funcX = function() {
this.funcY();
}

this.funcY = function() {
this.funcZ();
}
}

var car = new Car();

Prohibit unrelated scripts from running

When we develop modern web pages, we will use some third-party frameworks or libraries. Almost all of them have been tested and have relatively few bugs. However, when we debug our own scripts, we may accidentally jump into these files, causing additional debugging tasks. The solution is to prohibit these scripts that do not require debugging from running. For details, see this article: javascript-debugging-with-black-box.

在较复杂的调试情况下发现关键元素

在一些复杂的调试环境下我们可能要输出很多行的内容,这时候我们习惯性的会用console.log, console.debug, console.warn, console.info, console.error这些来进行区分,然后就可以在Inspector中进行过滤。不过有时候我们还是希望能够自定义显示样式,你可以用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’);

console.log()中你可以使用%s来代表一个字符串 , %i 来代表数字, 以及 %c 来代表自定义的样式。

监测指定函数的调用与参数

在Chrome中可以监测指定函数的调用情况以及参数:

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

这种方式能够让你实时监控到底啥参数被传入到了指定函数中。

Console中使用$进行元素查询

在Console中也可以使用来进行类似于querySelector那样基于CSS选择器的查询,(‘css-selector’) 会返回满足匹配的第一个元素,而$$(‘css-selector’) 会返回全部匹配元素。注意,如果你会多次使用到元素,那么别忘了将它们存入变量中。

Postman

很多人习惯用Postman进行API调试或者发起Ajax请求,不过别忘了你浏览器自带的也能做这个,并且你也不需要担心啥认证啊这些,因为Cookie都是自带帮你传送的,这些只要在network这个tab里就能进行,大概这样子:

DOM变化检测

DOM有时候还是很操蛋的,有时候压根不知道啥时候就变了,不过Chrome提供了一个小的功能就是当DOM发生变化的时候它会提醒你,你可以监测属性变化等等:

 以上就是关于十几个 实用的 JavaScript 调试小技巧图文代码详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.