调试JavaScript的权威指南

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值