语法错误:非法字符

lexer 读取不属于字符串文字的字符,并且该字符不能构成语言中的有效标记时,会发生 JavaScript 异常 "非法字符"。

¥The JavaScript exception "illegal character" occurs when the lexer reads a character that's not part of a string literal, and the character cannot constitute a valid token in the language.

信息

¥Message

SyntaxError: Invalid or unexpected token (V8-based)
SyntaxError: illegal character U+201C (Firefox)
SyntaxError: Invalid character '\u201c' (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

有一个解释器无法理解的无效字符。你应该将其放在字符串文字中或用另一个字符替换它。使用支持语法高亮的编辑器,并仔细检查代码是否存在不匹配的情况,例如减号 (-) 与破折号 () 或简单引号 (") 与非标准引号 (")。

¥There is an invalid character that the interpreter doesn't understand. You should either put it in a string literal or replace it with another character. 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 operators = ["+", "-", ×", "÷"];
// SyntaxError: illegal character U+00D7

添加 "×" 缺少的报价。

¥Add the missing quote for "×".

js
const operators = ["+", "-", "×", "÷"];

隐藏人物

¥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