语法错误:非法字符

当代码中存在不属于此位置的无效或意外标记时,就会发生 JavaScript 异常 "非法字符"。

¥The JavaScript exception "illegal character" occurs when there is an invalid or unexpected token that doesn't belong at this position in the code.

信息

¥Message

SyntaxError: Invalid character (Edge)
SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

存在不属于代码中此位置的无效或意外标记。使用支持语法高亮的编辑器,并仔细检查代码是否存在不匹配的情况,例如减号 (-) 与破折号 () 或简单引号 (") 与非标准引号 (")。

¥There is an invalid or unexpected token that doesn't belong at this position in the code. Use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign (-) versus a dash () or simple quotes (") versus non-standard quotation marks (").

示例

¥Examples

字符不匹配

¥Mismatched characters

有些字符看起来很相似,但会导致解析器无法解释你的代码。著名的例子是引号、减号或分号(希腊问号 (U+37e) 看起来相同)。

¥Some characters look similar, but will cause the parser to fail interpreting your code. Famous examples of this are quotes, the minus or semicolon (greek question mark (U+37e) looks same).

js
“This looks like a string”; // SyntaxError: illegal character
// “ and ” are not " but look like it

4213; // SyntaxError: illegal character
// – (en-dash) is not - but looks like it

const foo = "bar"; // SyntaxError: illegal character
// <37e> is not ; but looks like it

这应该有效:

¥This should work:

js
"This is actually a string";
42 - 13;
const foo = "bar";

一些编辑器和 IDE 会通知你,或者至少使用稍微不同的高亮,但不是全部。当你的代码发生类似情况并且你无法找到问题根源时,通常最好删除有问题的行并重新输入。

¥Some editors and IDEs will notify you or at least use a slightly different highlighting for it, but not all. When something like this happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it.

被遗忘的角色

¥Forgotten characters

很容易忘记这里或那里的某个角色。

¥It's easy to forget a character here or there.

js
const colors = ["#000", #333", "#666"];
// SyntaxError: illegal character

添加 "#333" 缺少的报价。

¥Add the missing quote for "#333".

js
const colors = ["#000", "#333", "#666"];

隐藏人物

¥Hidden characters

从外部源复制粘贴代码时,可能存在无效字符。小心!

¥When copy pasting code from external sources, there might be invalid characters. Watch out!

js
const foo = "bar";// SyntaxError: illegal character

在 Vim 等编辑器中检查这段代码时,你可以看到实际上有一个 零宽度空间 (ZWSP) (U+200B) 字符。

¥When inspecting this code in an editor like Vim, you can see that there is actually a zero-width space (ZWSP) (U+200B) character.

js
const foo = "bar";<200b>

也可以看看

¥See also