JavaScript 注释

发布于 2024-09-06 07:07:17 字数 2098 浏览 13 评论 0

在本教程中,您将了解 JavaScript 注释,为什么使用它们以及如何在示例的帮助下使用它们。JavaScript 注释是程序员可以添加的提示,以使他们的代码更易于阅读和理解。它们被 JavaScript 引擎完全忽略。


有两种方法可以向代码添加注释:

  • // -单行注释
  • /* */ -多行注释

单行注释

在 JavaScript 中,任何以 // 开头的行都是注释。例如,

name = "Jack";

// printing name on the console
console.log("Hello " + name);

在这里, // printing name on the console 是注释。

您还可以使用像这样的单条注释:

name = "Jack";

console.log("Hello " + name);  // printing name on the console

多行注释

在 Javascript 中, /**/ 之间的任何文本也是注释。例如,

/* The following program contains the source code for a game called Baghchal. 

Baghchal is a popular board game in Nepal where two players choose either sheep or tiger. It is played on a 5x5 grid.

For the player controlling the tiger to win, they must capture all the sheep. There are altogether 4 tigers on the board.

For the sheep to win, all tigers must be surrounded and cornered so that they cannot move. The player controlling the sheep has 20 sheep at his disposal.
*/

由于其余的源代码将用于实现游戏规则,因此上面的注释是一个很好的示例,您可以在其中使用多行注释。


使用注释进行调试

注释也可以用于禁用代码以阻止其执行。例如,

console.log("some code");
console.log("Error code);
console.log("other code");

如果在运行程序时遇到错误,则可以删除注释,而不是删除容易出错的代码,而可以通过注释禁止它执行。这可能是有价值的调试工具。

console.log("some code");
// console.log("Error code);
console.log("other code");

专家提示: 请记住使用注释的快捷方式;这真的很有帮助。对于大多数代码编辑器,对于 Windows 是 Ctrl + / ,对于 Mac 是 Cmd + /


使代码更容易理解

作为 JavaScript 开发人员,您不仅会编写代码,而且可能还必须修改其他开发人员编写的代码。如果您在代码上写注释,将来您将更容易理解代码。而且,您的其他开发人员将更容易理解代码。

作为一般的经验法则,请使用注释来解释您 为什么 做某事,而不是 如何 做某事,并且您是好人。注意: 注释不能替代用英语解释写得不好的代码的方法。您应该始终编写结构合理且易于解释的代码。然后,使用注释。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

伤感在游骋

暂无简介

0 文章
0 评论
21 人气
更多

推荐作者

花开柳相依

文章 0 评论 0

zyhello

文章 0 评论 0

故友

文章 0 评论 0

对风讲故事

文章 0 评论 0

Oo萌小芽oO

文章 0 评论 0

梦明

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文