Javascript 简明教程

JavaScript - Debugging

What is Debugging?

在 JavaScript 中调试是一个检查 JavaScript 代码并查找和修复错误的过程。开发人员在编码时总会出现错误。这些错误可能是逻辑错误、语法错误或运行时错误。程序或脚本中的错误称为软件缺陷。

Debugging in JavaScript is a process of examining JavaScript code and finding erros and fixing them. Every now and then, developers commit mistakes while coding. This error can be logical, syntax, or runtime errors. An error in a program or a script is referred to as a bug.

查找和修复软件缺陷的过程称为调试,这是开发过程的正常部分。本部分介绍可以帮助执行调试任务的工具和技术。

The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks.

让我们看一下不同的调试方法。

Let’s look at the different methods of debugging.

Use a JavaScript Debugger

调试器是一种将脚本执行的所有方面置于程序员控制之下的应用程序。调试器通过允许你检查和设置值以及控制执行流的接口,提供了对脚本状态的精细控制。

A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution.

将脚本加载到调试器中后,可以一次运行一行,或者指示在某些断点处停止。中止执行后,程序员可以检查脚本及其变量的状态,以确定是否有问题。你还可以观察变量的值的变化。

Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values.

如今,所有现代浏览器都带有内置调试器。可以使用浏览器的控制台来调试 JavaScript 代码。

Nowadays, all modern browser comes with built-in debuggers. You can use the console of the browser to debug the JavaScript code.

How to Open Console in the Browser?

在本部分,你将学习如何在不同的浏览器中打开控制台。

In this section, you will learn to open the console in different browsers.

Open Console in Chrome

按下以下键。

Press the Below keys.

  1. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J

  2. macOs − Cmd + Option + I or Cmd + Option + J

OR

  1. Step 1 − Open Chrome web browser and open the web page in a new window.

  2. Step 2 − Right-click anywhere on the web page.

  3. Step 3 − It will pop up menu. Select the last option, which is 'inspect'.

  4. Step 4 − It will open a Chrome developer tool.

  5. Step 5 − Go to the console tab.

Open Console in Firefox

按下以下键。

Press the Below keys.

  1. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J

  2. macOs − Cmd + Option + I or Cmd + Option + J

OR

  1. Step 1 − Open Firefox web browser and open the web page in a new window.

  2. Step 2 − Right-click anywhere on the web page.

  3. Step 3 − Select the last option from the popup menu, which is 'inspect(Q)'.

  4. Step 4 − It will open a developer tool.

  5. Step 5 − You can move from the 'inspector' tab to the 'console' tab.

Open Console in Microsoft Edge

按下以下键。

Press the Below keys.

  1. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J

  2. macOs − Cmd + Option + I or Cmd + Option + J

OR

  1. Step 1 − Open the Microsoft Edge browser.

  2. Step 2 − Right-click anywhere on the web page.

  3. Step 3 − Click on 'inspect' in the popup menu.

  4. Step 4 − You will see the developer tool is opened.

  5. Step 5 − Next, you can change the 'Elements' tab to the 'Console' tab in the developer tool.

Open Console in Safari

按下以下键。

Press the Below keys.

  1. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J

  2. macOs − Cmd + Option + I or Cmd + Option + J

OR

  1. Step 1 − Open the Safari web browser.

  2. Step 2 − Open the Safari main menu from the top menu bar.

  3. Step 3 − Choose 'preferences' in the dropdown menu. Next, choose the 'advanced' option.

  4. Step 4 − Check the checkbox named 'Enable Show Develop menu in menu bar' to enable the developer tool. Next, close the preference window.

  5. Step 5 − Next, reopen the main menu and select 'Develop’. After that, select the 'Show Error Console’.

Open Console in Opera

按下以下键。

Press the Below keys.

  1. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J

  2. macOs − Cmd + Option + I or Cmd + Option + J

OR

  1. Step 1 − Open the Opera browser.

  2. Step 2 − Open the main menu from the top corner.

  3. Step 3 − In the main menu, select the 'Developer’. It will open the sub-menu.

  4. Step 4 − In the submenu, select the 'developer tools’.

  5. Step 5 − Next, select the 'console’. It will open a console.

Using the console.log() method

console.log() 方法在网络浏览器的控制台中打印消息。 它可以打印原始值、对象、变量值等。

The console.log() method prints the message in the web browser’s console. It can print primitive values, objects, variable values, etc.

您可以在要调试的控制台中打印变量值。

You can print the variable’s value in the console you want to debug.

Syntax

用户可以使用下方的语法来使用console.log()方法。

Users can follow the syntax below to use the console.log() method.

Console.log(val1, val2, ...);

console.log()方法需要以逗号分隔的参数来在网络浏览器的控制台中打印。

The console.log() method takes the comma-separated arguments to print in the web browser’s console.

Example

在下方的代码中,我们对num1和num2变量的值进行加法。而在浏览器中,你会看到求和结果为32而不是5。

In the code below, we add the value of the num1 and num2 variables. In the browser, you can see that the sum is 32 rather than 5.

所以,你需要调试代码。

So, you are required to debug the code.

当你将num1和num2的类型打印到控制台时,它显示num1的类型是字符串。所以,它将num2变量的值转换成字符串类型,并用num1的值来附加它。

When you print the type of the num1 and num2 into the console, it shows that the type of the num1 is a string. So, it converts the value of the num2 variable into the string and appends it with the value of the num1.

<html>
<body>
   <div id = "output"> </div>
   <p>Note: To see the resullt in console, please open it before you run the code.</p>
   <script>
      let num1 = "3";
      let num2 = 2;
      let sum = num1 + num2;
      document.getElementById("output").innerHTML = "The sum is: " + sum;
      console.log("typeof num1 is " + typeof num1);
      console.log("typeof num2 is " + typeof num2);
   </script>
</body>
</html>
The sum is: 32
Note: To see the resullt in console, please open it before you run the code.

它将在网页控制台中生成如下结果:

It will produce the following result in the web console −

typeof num1 is string
VM75616:7 typeof num2 is number

Example

在下面的代码中,我们有一个包含不同属性的person对象。我们在网页浏览器中打印person对象的firstname和lastname属性。它打印的是undefined。

In the code below, we have a person object containing various properties. We print the firstname and lastname properties of the person object in the web browser. It prints undefined.

为了找到错误,你需要调试代码。接下来,我们在控制台中打印了对象,并发现Person对象并不包含firstname和lastname属性;相反,它包含’name’属性。

To find the error, you are required to debug the code. Next, we print the object in the console and found that the Person object doesn’t contain the firstname and lastname properties; instead of that, it contains the 'name' property.

<html>
<body>
   <div id = "demo"> </div>
   <p>Note: To see the resullt in console, please open it before you run the code.</p>
   <script>
      let output = document.getElementById("demo");
      let person = {
         name: "John",
         age: 25,
         city: "New York"
      }
      output.innerHTML = "The name of the person is: " + person.name + "<br>";
      output.innerHTML += "The city of the person is: " + person.city + "<br>";
      console.log(person);
   </script>
</body>
</html>
The name of the person is: John
The city of the person is: New York
Note: To see the resullt in console, please open it before you run the code.

它将在网页控制台中生成如下结果:

It will produce the following result in the web console −

{name: 'John', age: 25, city: 'New York'}

Using the debugger Keyword

你可以到浏览器的控制台去“source”面板来调试代码。

You can go to your browser’s console’s 'source' panel to debug the code.

'debugger’关键字允许你强制停止JavaScript代码的执行。

The 'debugger' keyword allows you to force-stop the execution of the JavaScript code.

停止JavaScript代码的执行允许你逐行调试代码。

Stopping the execution of the JavaScript code allows you to debug the code line-by-line.

一旦你找到错误或看起来一切正常,你就可以继续执行JavaScript代码。

Once you find the bug or everything looks fine, you can resume the execution of the JavaScript code.

你可以在浏览器中打开控制台并运行下面的代码。它会自动暂停代码的执行,然后你就可以观察变量的值来调试代码。

You can open the console and run the below code in the browser. It will automatically pause the code, and you can observe the values of the variables to debug the code.

Example

下面的例子与上面的例子相同。在打印对象属性的值之前,我们添加了’debugger’关键字。

The below example is the same as above. We have added the 'debugger' keyword before it prints the values of the object properties.

它会在打印属性的值之前暂停代码的执行。在那之后,当你点击继续按钮时,它将继续执行代码。

It will pause the execution of the code before printing the values of properties. After that, when you click on the resume button, it will resume the execution of the code.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      const person = {
         name: "John",
         age: 25,
         city: "New York"
      }
      debugger;
      output.innerHTML = "The name of the person is: " + person.name + "<br>";
      output.innerHTML += "The city of the person is: " + person.city;
   </script>
</body>
</html>
The name of the person is: John
The city of the person is: New York

你将在控制台中看到与下方截屏相似的结果。为了在控制台中看到结果,请在运行代码之前打开控制台。

You will see the result in console similar to the below screenshot. To see the resullt in console, please open it before you run the code.

debugging debugger keyword

上方的图片显示了浏览器窗口顶部的暂停按钮,以及右下角的对象或变量。通过这种方式,你能够检查变量值并在代码中调试来修复错误。

The above image shows the pause button at the top of the browser window and the object or variables in the bottom-right corner. This way, you can check variable values and debug the code to fix the bugs.

Setting Break Points in the Browser’s Debugger

设置断点与使用’debugger’关键字来调试JavaScript代码是相同。所以这是一个替代方式。

Setting up breakpoints is the same as using the 'debugger' keyword to debug the JavaScript code. So, this is an alternative way.

在’source’面板中,你可以点击你要添加断点的那行行号,如下方的图片所示。

In the 'source' panel, you can click on the line number where you want to add a breakpoint, as shown in the image below.

之后,当您执行 JavaScript 代码时,它会停止代码执行,您可以在右侧看到变量值。

After that, when you execute the JavaScript code, it will stop the execution of the code, and you can observe the variable values on the right side.

debugging break point

Example

我们已在以下示例代码中定义了 test() 函数。test() 函数连接了 str1 和 str2 字符串。

We have defined the test() function in the example code below. The test() function concatenates the str1 and str2 strings.

我们在开发人员工具的浏览器的“source”面板中打开该面板。之后,我们在“let res = str1.concat(str2);”行上添加断点。这样,调试器将在此行停止代码执行,您可以单击恢复按钮继续执行代码。

We have opened the 'source' panel in the browser in the developer tool. After that, we have added the breakpoint on the line 'let res = str1.concat(str2);'. So, the debugger will stop the execution of the code at this line, and you can click the resume button to resume the execution of the code.

<html>
<body>
   <div id = "output">The resultant string after appending str2 to str1 is: </div>
   <script>
      function test() {
         let str1 = "Hi";
         let str2 = "";
         let res = str1.concat(str2);
         document.getElementById("output").innerHTML += res;
      }
      test();
   </script>
</body>
</html>
The resultant string after appending str2 to str1 is: Hi

你将在控制台中看到与下方截屏相似的结果。为了在控制台中看到结果,请在运行代码之前打开控制台。

You will see the result in console similar to the below screenshot. To see the resullt in console, please open it before you run the code.

debugging break point output

Useful Tips for Developers

你可以记住以下提示以减少脚本中的错误数量并简化调试过程 −

You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −

  1. Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.

  2. Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements. You can use the code formatters in the IDE.

  3. Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements and test and reuse portions of code with minimal effort.

  4. Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the variable’s contents or the function’s purpose.

  5. Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.

  6. Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.

  7. Use descriptive variable and function names and avoid using single-character names.

  8. Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).

  9. Watch your equal signs. You should not use a single = for comparison purposes.

  10. Declare variables explicitly using the var keyword.