博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
调试JavaScript的权威指南
阅读量:2513 次
发布时间:2019-05-11

本文共 9323 字,大约阅读时间需要 31 分钟。

Debugging is one of those skills that’s core to the activity of a programmer.

调试是程序员活动的核心技能之一。

Sometimes we do our best work, yet the program is not working correctly, for example it’s crashing, it’s just slow or it’s printing wrong information.

有时我们会尽力而为,但是程序无法正常运行,例如,它崩溃了,速度很慢或正在打印错误的信息。

What do you do when a program you wrote is not behaving like you expect?

当您编写的程序表现不理想时,您会怎么做?

You start debugging it.

您开始调试它。

找出错误可能在哪里 (Figuring out where the error could be)

The first step is always to look at what is happening, and trying to determine where is the problem coming from. Is it a problem in the environment? Is it a problem in the input you gave to the program? Is it a one-time crash due to too much memory usage? Or is it happening every time you run it?

第一步始终是查看正在发生的事情,并尝试确定问题的根源。 环境有问题吗? 您提供给程序的输入是否有问题? 是否由于内存使用过多而导致一次崩溃? 还是每次运行都会发生?

Those are all key information to start going in the right direction when figuring out a problem.

这些都是解决问题时开始朝正确方向发展的关键信息。

Once you have some sort of idea where the error is coming from, you can start checking that specific part of code.

一旦弄清错误的来源,就可以开始检查代码的特定部分。

阅读代码 (Read the code)

The simplest way to debug, at least in terms of tooling, is by reading the code you wrote. Aloud. There is some magical thing in hearing from our own voice that does not happen when you read in silence.

至少在工具方面,最简单的调试方法是阅读您编写的代码。 大声 从我们自己的声音中听到的声音有些不可思议的事情,而您在静默地阅读时却不会发生。

Often times I found problems in this way.

我常常以这种方式发现问题。

使用控制台 (Using the console)

If reading the code reveals nothing to you, the next logical step is to start adding a few lines into your code that can shed some light.

如果阅读该代码对您没有任何帮助,那么下一步的逻辑就是开始向您的代码中添加几行内容,以使您有所了解。

In JavaScript frontend code what you’ll often do is to use alert() and console.log (and its cool friends).

在JavaScript前端代码中,通常要做的是使用alert()console.log (及其友善的朋友)。

Consider this line:

考虑这一行:

const a = calculateA()const b = calculateB()const result = a + b

Somehow the result is not correctly calculated, so you can start by adding alert(a) and alert(b) before calculating the result, and the browser will open two alert panels when it executes the code.

以某种方式不能正确计算结果,因此可以在计算结果之前先添加alert(a)alert(b) ,然后浏览器在执行代码时将打开两个警报面板。

const a = calculateA()const b = calculateB()alert(a)alert(b)const result = a + b

This works fine if what you are passing to alert() is a string or a number. As soon as you have an array or an object things start to be too complicated for alert(), and you can use the . Starting with console.log():

如果您要传递给alert()是字符串或数字,则此方法很好。 一旦有了数组或对象,对于alert()来说事情就变得太复杂了,可以使用 。 从console.log()

const a = calculateA()const b = calculateB()console.log(a)console.log(b)const result = a + b

The value is printed in the JavaScript console of the browser developer tools. For convenience I’m explaining debugging in the Chrome DevTools here, but the general concepts apply to all browsers, with some differences in terms of features supported.

该值显示在浏览器开发人员工具JavaScript控制台中。 为了方便起见,我在这里解释如何在Chrome DevTools中进行调试,但是一般概念适用于所有浏览器,但在支持的功能方面有所不同。

See the

查看的

Chrome开发工具 (The Chrome Dev Tools)

The result of the console.log() calls is printed to the JavaScript console. This is a tool that’s more or less common to every browser:

console.log()调用的结果将打印到JavaScript控制台。 这是每个浏览器或多或少通用的工具:

Browser console

The tool is very powerful and lets you print complex objects or arrays and you can inspect every property of them.

该工具非常强大,可以打印复杂的对象或数组,并可以检查它们的每个属性。

In the post you can see all the options and details of working with it, so I’m not explaining all the details here.

在帖子中,您可以看到使用它的所有选项和详细信息,因此在这里我不解释所有详细信息。

调试器 (The debugger)

The debugger is the most powerful tool in the browser developer tools, and it’s found in the Sources panel:

调试器是浏览器开发人员工具中最强大的工具,可在“ 源”面板中找到:

The debugger

The top part of the screen shows the files navigator.

屏幕的顶部显示文件导航器。

You can select any file and inspect it on the right. This is very important to set breakpoints, as we’ll see later.

您可以选择任何文件并在右侧检查它。 这对于设置断点非常重要,我们将在后面看到。

The bottom part is the actual debugger.

底部是实际的调试器。

断点 (Breakpoints)

When the browser loads a page, the JavaScript code is executed until a breakpoint is met.

当浏览器加载页面时,将执行JavaScript代码,直到遇到断点为止。

At this point the execution is halted and you can inspect all about your running program.

此时,执行被暂停,您可以检查所有有关正在运行的程序。

You can check the variables values, and resume the execution of the program one line at a time.

您可以检查变量值,然后一次只恢复一行程序的执行。

But first, what is a breakpoint? In its simple form, a breakpoint is a breakpoint instruction put in your code. When the browser meets it, it stops.

但是首先,什么是断点? 简单来说,断点就是代码中的breakpoint指令。 当浏览器遇到它时,它停止。

This is a good option while developing. Another option is to open the file in the Sources panel and click the number on the line you want to add a breakpoint:

这是开发时的好选择。 另一个选项是在“源”面板中打开文件,然后单击要添加断点的行上的数字:

Added breakpoint

Clicking again the breakpoint will remove it.

再次单击断点将其删除。

After you add a breakpoint you can reload the page and the code will stop at that execution point when it finds the breakpoint.

添加断点后,您可以重新加载页面,并且代码在找到断点时将在该执行点停止。

As you add the breakpoint you can see in the Breakpoints panel that form.js on line 7 has the breakpoint. You can see all your breakpoints there, and disable them temporarily.

添加断点时,您可以在“ 断点”面板中form.js7行的form.js具有断点。 您可以在那里查看所有断点,并暂时禁用它们。

There are other types of breakpoints as well:

还有其他类型的断点:

  • XHR/fetch breakpoints: triggered when any network request is sent

    XHR /提取断点 :发送任何网络请求时触发

  • DOM breakpoints: triggered when a DOM element changes

    DOM断点 :当DOM元素更改时触发

  • Event listener breakpoints: triggered when some event happens, like a mouse click

    事件侦听器断点 :当某些事件发生时触发,例如单击鼠标

Breakpoints

范围 (Scope)

In this example I set a breakpoint inside an event listener, so I had to submit a form to trigger the it:

在此示例中,我在事件监听器中设置了一个断点,因此我必须提交一个表单来触发它:

Triggered breakpoint

Now all the variables that are in the scope are printed, with their respective values. You can edit those variables by double clicking them.

现在,将打印范围内的所有变量及其各自的值。 您可以通过双击来编辑这些变量。

观察变量和表达式 (Watch variables and expressions)

Right to the Scope panel there’s the Watch panel.

在“ 作用域”面板的右边是“ 监视”面板。

It has a + button which you can use to add any expression. For example adding name will print the name variable value, in the example Flavio. You can add name.toUpperCase() and it will print FLAVIO:

它有一个+按钮,可用于添加任何表达式。 例如,在示例Flavio ,添加name将打印name变量值。 您可以添加name.toUpperCase() ,它将显示FLAVIO

Watch expressions

恢复执行 (Resume the execution)

Now the scripts are all halted since the breakpoint stopped the execution.

现在,自断点停止执行以来,脚本均已暂停。

There is a set of buttons above the “Paused on breakpoint” banner that let you alter this state.

在“在断点处暂停”标语上方有一组按钮,可让您更改此状态。

The first is in blue. Clicking it resumes the normal script execution.

第一个是蓝色。 单击它可恢复正常脚本执行。

The second button is step over, and it resumes execution until the next line, and stops again.

第二个按钮是step over ,它将继续执行直到下一行,然后再次停止。

The next button perform a step into operation: goes into the function being executed, letting you go into the details of it.

下一步按钮执行步投产 :进入正在执行的功能,让你进入它的细节。

Step out is the opposite: goes back to the outer function calling this one.

退出是相反的情况:返回调用此函数的外部函数。

Those are the main ways to control the flow during debugging.

这些是调试期间控制流的主要方法。

编辑脚本 (Edit scripts)

From this devtools screen you can edit any script, also while the script is halted in its execution. Just edit the file and press cmd-S on Mac or ctrl-S on Windows/Linux.

在这个devtools屏幕上,您可以编辑任何脚本,也可以在脚本停止执行时进行编辑。 只需编辑文件,然后在Mac上按cmd-S或在Windows / Linux上按ctrl-S。

Of course the changes are not persisted to disk unless you are working locally and set up workspaces in the devtools, a more advanced topic.

当然,除非您在本地工作并在devtools(一个更高级的主题)中设置工作区,否则更改不会持久保存在磁盘上。

检查调用堆栈 (Inspect the call stack)

The call stack is great to see how many functions levels you are deep into the JavaScript code. It lets you move up in the stack too by clicking each function name:

调用堆栈非常适合您了解JavaScript代码有多少个功能级别。 通过单击每个函数名称,它也可以使您在堆栈中向上移动:

Call stack

黑盒脚本 (Blackbox scripts)

Often times you work with libraries where you don’t want to “step into”, you trust them and you don’t want to see their code in the call stack, for example. Like in the above case for validator.min.js, which I use for email validation.

例如,通常您在不想“涉足”的库中工作时,您会信任它们并且不想在调用堆栈中看到它们的代码。 就像上面的validator.min.js案例一样,我将其用于电子邮件验证。

I trust it does a good job, so I can right-click it in the call stack and press Blackbox script. From then on, it’s impossible to step into this script code, and you happily work on just your own application code.

我相信它做得很好,所以我可以在调用堆栈中右键单击它,然后按Blackbox script 。 从那时起,就不可能进入此脚本代码,而您可以快乐地处理自己的应用程序代码。

使用浏览器devtools调试Node.js (Use the browser devtools to debug Node.js)

Since Node.js is built on the same engine of Chrome, , you can link the 2 and use the Chrome DevTools to inspect the execution of Node.js applications.

由于Node.js是基于Chrome 的同一引擎构建的,因此您可以链接两者并使用Chrome DevTools检查Node.js应用程序的执行情况。

Open your and run

打开并运行

node --inspect

node-inspect

Then in Chrome type this URL: about://inspect.

然后在Chrome中输入以下URL: about://inspect

node-link-browser

Click the Open dedicated DevTools for Node link next to the Node target, and you’ll have access to Node.js in the browser DevTools:

单击“节点”目标旁边的“打开专用于节点的专用DevTools”链接,您将可以在浏览器DevTools中访问Node.js:

node-console

Make sure you click that, and not the inspect link down below, as it tool auto-reconnects to the Node.js instance when we restart it - pretty handy!

确保单击该按钮,而不单击下面的检查链接,因为它在我们重新启动时会自动重新连接到Node.js实例,因此非常方便!

翻译自:

转载地址:http://khqgb.baihongyu.com/

你可能感兴趣的文章
VS2013 添加已有文件夹
查看>>
python 计时程序运行时间
查看>>
【Shell脚本学习4】几种常见的Shell
查看>>
Git学习系列-Git基本概念
查看>>
c#多个程序集使用app.config 的解决办法
查看>>
模仿网站登录注册
查看>>
Linux+Apache+PHP+MySQL服务器环境配置(CentOS篇)
查看>>
Linux下获取本机IP地址的代码
查看>>
(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误
查看>>
flex布局
查看>>
python-----python的文件操作
查看>>
java Graphics2d消除锯齿,使字体平滑显示
查看>>
控件中添加的成员变量value和control的区别
查看>>
Spring Boot Docker 实战
查看>>
Div Vertical Menu ver3
查看>>
Git简明操作
查看>>
InnoDB为什么要使用auto_Increment
查看>>
课堂练习之买书打折最便宜
查看>>
定义函数
查看>>
网络虚拟化技术(二): TUN/TAP MACVLAN MACVTAP
查看>>