语法错误:意外的标记
当需要特定的语言构造但提供了其他内容时,就会发生 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.
信息
错误类型
什么地方出了错?
示例
预期表达
¥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