语法错误:意外的标记

当需要特定的语言构造但提供了其他内容时,就会发生 JavaScript 异常 "意外的标记"。这可能是一个简单的错字。

¥The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

信息

¥Message

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

期望有一个特定的语言结构,但也提供了其他东西。这可能是一个简单的错字。

¥A specific language construct was expected, but something else was provided. This might be a simple typo.

示例

¥Examples

预期表达

¥Expression expected

例如,当链接表达式时,不允许使用尾随逗号。

¥For example, when chaining expressions, trailing commas are not allowed.

js
for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// Uncaught SyntaxError: expected expression, got ';'

正确的做法是省略逗号或添加另一个表达式:

¥Correct would be omitting the comma or adding another expression:

js
for (let i = 0; i < 5; ++i) {
  console.log(i);
}

括号不够

¥Not enough parentheses

有时,你会在 if 语句周围省略括号:

¥Sometimes, you leave out parentheses around if statements:

js
function round(n, upperBound, lowerBound) {
  if (n > upperBound) || (n < lowerBound) { // Not enough parenthese here!
    throw new Error(`Number ${n} is more than ${upperBound} or less than ${lowerBound}`);
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'

括号乍一看可能是正确的,但请注意 || 是如何位于括号之外的。正确的做法是在 || 两边加上括号:

¥The parentheses may look correct at first, but note how the || is outside the parentheses. Correct would be putting parentheses around the ||:

js
function round(n, upperBound, lowerBound) {
  if ((n > upperBound) || (n < lowerBound)) {
    throw new Error(
      `Number ${n} is more than ${upperBound} or less than ${lowerBound}`,
    );
  } else if (n < (upperBound + lowerBound) / 2) {
    return lowerBound;
  } else {
    return upperBound;
  }
}

也可以看看

¥See also