语法错误: 意外的标记

JavaScript 异常 "unexpected token" 发生在解析器在给定位置没有看到它识别的标记时,因此无法理解程序的结构。这可能是一个简单的拼写错误。

消息

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)

错误类型

出了什么问题?

预期特定语言结构,但提供了其他内容。这可能是一个简单的拼写错误。

示例

预期表达式

例如,在连接表达式时,不允许尾随逗号。

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

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

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

括号不足

有时,您会在 `if` 语句周围省略括号

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 '||'

括号乍一看可能是正确的,但请注意 `||` 如何在括号之外。正确的是将括号放在 `||` 周围

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;
  }
}

另请参阅