JavaScript 中的断点
在本文中,我们将讨论断点的用法和好处,以及如何借助 debugger
关键字和浏览器的调试器模式来调试我们的 JavaScript 代码。
断点
大多数时候,我们的程序代码包含很少的逻辑语法错误,并且我们的程序没有按照给定的语句提供所需的结果。因此,为了解决错误和调试我们的程序代码,我们需要停止执行并检查每一步的执行流程。
我们在程序中使用断点来停止执行,各种编程语言都专门包含断点关键字。
断点关键字在代码运行期间停止执行,因为大多数时候,错误不会显示任何错误消息或日志,我们需要找出实际问题所在。
JavaScript 中的断点
调试是一个棘手的过程,现在大多数浏览器都提供了内置的 JavaScript 调试器。我们可以使用调试器设置断点并定义我们需要停止执行的位置。
我们可以在代码执行时在运行时检查变量值。
我们可以通过按 F12 键在浏览器中激活调试,然后从调试器菜单中选择 Console
部分。如果我们的浏览器支持调试,我们可以使用 console.log()
方法来显示和检查值。
控制台
的示例:
<!DOCTYPE html>
<html>
<body>
<h1>Delftstack learning</h1>
<h2>JavaScript debugger keyword example</h2>
<p>You can on debugger with F12 key and select console in debugger menu.</p>
<script>
a = 2;
b = 4;
sum = a + b;
console.log(c); // it will display the value of sum variable
</script>
</body>
</html>
在上面的 HTML 源代码中,我们使用了 console.log()
默认方法来显示变量 a
和 b
的总和;我们可以看到调试器模式的登录控制台
部分。
我们可以在调试器窗口中为 JavaScript 代码设置断点,在每个断点处都会停止执行,这将有助于检查 JavaScript 值。我们可以使用调试器窗口中的播放按钮再次恢复执行。
JavaScript 中的 Debugger
关键字
JavaScript debugger
关键字在代码语句中用于停止执行;它执行与我们在调试器中设置断点相同的功能。
调试器
的示例:
<!DOCTYPE html>
<html>
<body>
<h1>Delftstack learning</h1>
<h2>JavaScript debugger keyword example</h2>
<p id="test"></p>
<p>You can on debugger and see the execution will be stop at third line.</p>
<script>
let sum = 15 + 5;
debugger; // to stop execution
document.getElementById("test").innerHTML = sum;
</script>
</body>
</html>
在上面的 HTML 源代码中,我们在 JavaScript 代码中使用了 debugger
关键字来停止执行并使用 getElementById("id").innerHTML
将 sum
变量分配给段落。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。