语法错误:丢失的 ; 声明之前

当某处缺少分号 (;) 并且无法通过 自动分号插入 (ASI) 添加时,会发生 JavaScript 异常 "丢失的 ; 声明之前"。你需要提供一个分号,以便 JavaScript 能够正确解析源代码。

¥The JavaScript exception "missing ; before statement" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (ASI). You need to provide a semicolon, so that JavaScript can parse the source code correctly.

信息

¥Message

SyntaxError: Expected ';' (Edge)
SyntaxError: missing ; before statement (Firefox)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

某处缺少分号 (;)。JavaScript 语句 必须以分号终止。其中一些受到 自动分号插入 (ASI) 的影响,但在这种情况下你需要提供分号,以便 JavaScript 可以正确解析源代码。

¥There is a semicolon (;) missing somewhere. JavaScript statements must be terminated with semicolons. Some of them are affected by automatic semicolon insertion (ASI), but in this case you need to provide a semicolon, so that JavaScript can parse the source code correctly.

但是,通常情况下,此错误只是另一个错误的结果,例如未正确转义字符串或错误地使用 var。你也可能在某个地方有太多括号。抛出此错误时请仔细检查语法。

¥However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. You might also have too many parenthesis somewhere. Carefully check the syntax when this error is thrown.

示例

¥Examples

未转义的字符串

¥Unescaped strings

当未正确转义字符串且 JavaScript 引擎已预期字符串结尾时,很容易发生此错误。例如:

¥This error can occur easily when not escaping strings properly and the JavaScript engine is expecting the end of your string already. For example:

js
const foo = 'Tom's bar';
// SyntaxError: missing ; before statement

你可以使用双引号,或转义撇号:

¥You can use double quotes, or escape the apostrophe:

js
const foo = "Tom's bar";
// OR
const foo = 'Tom\'s bar';

使用关键字声明属性

¥Declaring properties with keyword

不能使用 letconstvar 声明来声明对象或数组的属性。

¥You cannot declare properties of an object or array with a let, const, or var declaration.

js
const obj = {};
const obj.foo = "hi"; // SyntaxError missing ; before statement

const array = [];
const array[0] = "there"; // SyntaxError missing ; before statement

相反,省略关键字:

¥Instead, omit the keyword:

js
const obj = {};
obj.foo = "hi";

const array = [];
array[0] = "there";

不良关键词

¥Bad keywords

如果你来自另一种编程语言,那么在 JavaScript 中使用含义不同或根本没有含义的关键字也很常见:

¥If you come from another programming language, it is also common to use keywords that don't mean the same or have no meaning at all in JavaScript:

js
def print(info) {
  console.log(info);
} // SyntaxError missing ; before statement

相反,使用 function 而不是 def

¥Instead, use function instead of def:

js
function print(info) {
  console.log(info);
}

也可以看看