aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/illegal_character/index.html
blob: 16367c43a215adda5d64ffbe512bcce5262768f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
---
title: 'SyntaxError: illegal character'
slug: Web/JavaScript/Reference/Errors/Illegal_character
tags:
  - JavaScript
  - 语法错误
translation_of: Web/JavaScript/Reference/Errors/Illegal_character
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="错误提示">错误提示</h2>

<pre class="syntaxbox">SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)
</pre>

<h2 id="错误类型">错误类型</h2>

<p>{{jsxref("SyntaxError")}}</p>

<h2 id="哪里出错了?">哪里出错了?</h2>

<p>在代码中有非法的或者不期望出现的标记符号出现在不该出现的位置。请使用支持语法高亮功能的编辑器仔细检查你的代码,看看是否存在张冠李戴的情况,比如减号 (<code> - </code>) 与连接符 (<code></code>) ,或者是英文双引号 (<code> " </code>) 与中文双引号 (<code></code>)。</p>

<h2 id="示例">示例</h2>

<h3 id="错配字符">错配字符</h3>

<p>一些字符看起来会很相像,但是会导致于语法解析器解析代码失败。</p>

<pre class="brush: js example-bad">“This looks like a string”;
// SyntaxError: illegal character

42 – 13;
// SyntaxError: illegal character
</pre>

<p>下面这样是可以正常运行的:</p>

<pre class="brush: js example-good">"This is actually a string";

42 - 13;
</pre>

<h3 id="遗漏的字符">遗漏的字符</h3>

<p>很容易就会在这里或那里遗漏一些字符。</p>

<pre class="brush: js example-bad">var colors = ['#000', #333', '#666'];
// SyntaxError: illegal character
</pre>

<p>把遗漏的引号给 '#333' 添加上。</p>

<pre class="brush: js example-good">var colors = ['#000', '#333', '#666'];</pre>

<h3 id="隐藏字符">隐藏字符</h3>

<p>当从外部复制粘贴代码的时候,有可能就有非法的隐藏字符的存在,需要引起注意!</p>

<pre class="brush: js example-bad">var foo = 'bar';​
// SyntaxError: illegal character
</pre>

<p>当使用文本编辑器如VIM进行探测的时候,可以发现这里存在一个零宽空格<a href="https://en.wikipedia.org/wiki/Zero-width_space"> (ZWSP) (U+200B)</a> 。</p>

<pre class="brush: js">var foo = 'bar';​&lt;200b&gt;</pre>

<h2 id="相关内容">相关内容</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li>
</ul>