语法错误:意外的标记

当解析器在给定位置看不到它识别的标记时,会发生 JavaScript 异常 "意外的标记",因此它无法理解程序的结构。这可能是一个简单的错字。

¥The JavaScript exceptions "unexpected token" occur when the parser does not see a token it recognizes at the given position, so it cannot make sense of the structure of the program. This might be a simple typo.

信息

¥Message

SyntaxError: Unexpected token ';' (V8-based)
SyntaxError: Unexpected identifier 'x' (V8-based)
SyntaxError: Unexpected number (V8-based)
SyntaxError: Unexpected string (V8-based)
SyntaxError: Unexpected regular expression (V8-based)
SyntaxError: Unexpected template string (V8-based)

SyntaxError: unexpected token: identifier (Firefox)
SyntaxError: expected expression, got "x" (Firefox)
SyntaxError: expected property name, got "x" (Firefox)
SyntaxError: expected target, got "x" (Firefox)
SyntaxError: expected meta, got "x" (Firefox)
SyntaxError: expected rest argument name, got "x" (Firefox)
SyntaxError: expected closing parenthesis, got "x" (Firefox)

错误类型

¥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