语法错误:函数体后面缺少 }

当在某处创建函数时出现语法错误时,就会出现 JavaScript 异常 "函数体后面缺少 }"。检查右大括号或圆括号的顺序是否正确。

¥The JavaScript exception "missing } after function body" occurs when there is a syntax mistake when creating a function somewhere. Check if any closing curly braces or parenthesis are in the correct order.

信息

¥Message

SyntaxError: missing } after function body (Firefox)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

在某处创建函数时存在语法错误。还要检查任何右大括号或圆括号的顺序是否正确。更好地缩进或格式化代码也可能会帮助你看清丛林。

¥There is a syntax mistake when creating a function somewhere. Also check if any closing curly braces or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle.

示例

¥Examples

忘记关闭大括号

¥Forgotten closing curly bracket

通常,函数代码中缺少大括号:

¥Oftentimes, there is a missing curly bracket in your function code:

js
function charge() {
  if (sunny) {
    useSolarCells();
  } else {
    promptBikeRide();
}

正确的是:

¥Correct would be:

js
function charge() {
  if (sunny) {
    useSolarCells();
  } else {
    promptBikeRide();
  }
}

例如,当使用 IIFEs 或其他使用大量不同括号和大括号的结构时,它可能会更加模糊。

¥It can be more obscure when using IIFEs or other constructs that use a lot of different parenthesis and curly braces, for example.

js
(function () {
  if (Math.random() < 0.01) {
    doSomething();
  }
)();

通常,不同的缩进或双重检查缩进有助于发现这些错误。

¥Oftentimes, indenting differently or double checking indentation helps to spot these errors.

js
(function () {
  if (Math.random() < 0.01) {
    doSomething();
  }
})();

也可以看看

¥See also