JavaScript 注释

x33g5p2x  于2022-04-06 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(245)

在本教程中,您将了解 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 开发人员,您不仅要编写代码,还可能需要修改其他开发人员编写的代码。
    如果你在你的代码上写注释,你以后会更容易理解代码。此外,您的开发人员将更容易理解代码。
一般的经验法则是,使用评论来解释你为什么做某事而不是你如何做某事。
    注:注释不是解释糟糕代码的方法。您应该始终编写结构良好、简明易懂的代码,然后使用注释。

上一教程 :JS Operators                                         下一教程 :JS Type Conversion

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/comments

相关文章

微信公众号

最新文章

更多