JavaScript 单行注释和块注释写法

JavaScript 中,// 注释到本行末尾,/* 与 */ 之间是块注释。注释用于解释决定或暂时停用代码。收到源码的人仍可阅读注释。

编写单行注释和块注释

// This is a comment.
const count = 3; // A comment can follow code.

/*
  A block comment can span multiple lines.
  It ends at the closing marker.
*/
const enabled = true;

// 之前的代码会照常运行。块注释可以跨行,行首的星号只是排版习惯。词法规则 说明了空白和注释的规则。适合记录单位、选择原因或必须遵守的条件。

在完整示例中只改一条注释

将示例以 UTF-8 保存为 comments.html 后打开。15 × 3 显示 Total: 45 minutes。只去掉 // total += 5; 开头的 //,保存并刷新后得到 50。恢复注释后回到 45。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Practice JavaScript comments</title>
</head>
<body>
<h1>Change an example with comments</h1>
<p id="output"></p>
<pre id="markers"></pre>
<script>
const minutes = 15; // Minutes per session
const sessions = 3;
/*
  The base total includes work time only.
  Uncomment the line below to add five minutes.
*/
let total = minutes * sessions;
// total += 5;
document.getElementById("output").textContent = `Total: ${total} minutes`;

// Markers inside these quotes are part of the strings.
const lineMarker = "//";
const blockMarker = "/* note */";
document.getElementById("markers").textContent =
  `Markers in strings: ${lineMarker}, ${blockMarker}`;
</script>
</body>
</html>

字符串 // 和 /* note */ 会按原样显示。全局删除 // 也可能破坏字符串中的 URL。

检查嵌套、语法与可见范围

块注释在第一个 */ 结束,不能嵌套。如果要暂时禁用已含块注释的代码,用编辑器逐行注释。脚本之外的 HTML 使用 <!-- ... -->。注释无法代替必要的运算符或括号。

const total = 2 /* first value */ + 3; // 5
const text = "// these markers are part of the string";

发送到浏览器的脚本注释可以被查看。不要将密码、秘密密钥或个人信息放进客户端代码。修改代码时也要核对注释。

注释中的换行何时改变返回值

在 Console 运行以下代码。return 与表达式之间的块注释如果含换行,就会被视为存在行终止符。自动分号插入规则 使函数在没有返回值的情况下结束。

{
  function inlineComment() {
    return /* no line break */ 5;
  }

  function multilineComment() {
    return /* this comment
      contains a line break */ 5;
  }

  function groupedExpression() {
    return (
      /* the expression starts on the return line */
      5
    );
  }

  console.log(inlineComment());      // 5
  console.log(multilineComment());   // undefined
  console.log(groupedExpression());  // 5
}

输出依次是 5、undefined、5。将长注释放在 return 前一行,或在同一行先写左括号再换行。返回值意外丢失时,先检查表达式之前是否换行。