Javascript 没有“意外令牌非法”的明显原因

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12719859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:06:30  来源:igfitidea点击:

No visible cause for "Unexpected token ILLEGAL"

javascriptsyntax-errorillegal-characters

提问by bfavaretto

I'm getting this JavaScript error on my console:

我在控制台上收到此 JavaScript 错误:

Uncaught SyntaxError: Unexpected token ILLEGAL

未捕获的语法错误:意外的令牌非法

This is my code:

这是我的代码:

var foo = 'bar';?

It's super simple, as you can see. How could it be causing a syntax error?

如您所见,这非常简单。它怎么会导致语法错误?

回答by bfavaretto

The error

错误

When code is parsed by the JavaScript interpreter, it gets broken into pieces called "tokens". When a token cannot be classified into one of the four basic token types, it gets labelled "ILLEGAL" on most implementations, and this error is thrown.

当 JavaScript 解释器解析代码时,它会被分解成称为“令牌”的部分。当令牌不能归类为四种基本令牌类型之一时,它会在大多数实现中被标记为“非法”,并抛出此错误。

The same error is raised if, for example, you try to run a js file with a rogue @character, a misplaced curly brace, bracket, "smart quotes", single quotes not enclosed properly (e.g. this.run('dev1)) and so on.

例如,如果您尝试运行带有流氓@字符、错位的花括号、括号、“智能引号”、未正确括起来的单引号(例如this.run('dev1))等的 js 文件,则会引发相同的错误。

A lot of different situations can cause this error. But if you don't have any obvious syntax error or illegal character, it may be caused by an invisibleillegal character. That's what this answer is about.

许多不同的情况都可能导致此错误。但是如果你没有任何明显的语法错误或非法字符,它可能是由一个不可见的非法字符引起的。这就是这个答案的内容。

But I can't see anything illegal!

但我看不到任何违法行为!

There is an invisible character in the code, right after the semicolon. It's the Unicode U+200BZero-width spacecharacter (a.k.a. ZWSP, HTML entity ​). That character is known to cause the Unexpected token ILLEGALJavaScript syntax error.

代码中有一个不可见的字符,就在分号之后。它是UnicodeU+200B零宽度空格字符(又名ZWSP,HTML 实体​)。已知该字符会导致Unexpected token ILLEGALJavaScript 语法错误。

And where did it come from?

它是从哪里来的?

I can't tell for sure, but my bet is on jsfiddle. If you paste code from there, it's very likely to include one or more U+200Bcharacters. It seems the tool uses that character to control word-wrapping on long strings.

我不能肯定,但我的赌注是jsfiddle。如果您从那里粘贴代码,则很可能包含一个或多个U+200B字符。该工具似乎使用该字符来控制长字符串的自动换行。

UPDATE 2013-01-07

After the latest jsfiddle update, it's now showing the character as a red dotlike codepen does. Apparently, it's also not inserting U+200Bcharacters on its own anymore, so this problem should be less frequent from now on.

UPDATE 2015-03-17

Vagrantappears to sometimes cause this issue as well, due to a bug in VirtualBox. The solution, as per this blog postis to set sendfile off;in your nginx config, or EnableSendfile Offif you use Apache.

更新 2013-01-07

在最新的jsfiddle 更新之后它现在像 codepen 一样将角色显示为红点显然,它也U+200B不再单独插入字符,所以从现在开始这个问题应该不那么频繁了。

更新 2015-03-17

由于VirtualBox 中的错误,Vagrant有时似乎也会导致此问题。根据这篇博文,解决方案是sendfile off;在您的 nginx 配置中进行设置,或者EnableSendfile Off如果您使用 Apache。

It's also been reportedthat code pasted from the Chrome developer tools may include that character, but I was unable to reproduce that with the current version (22.0.1229.79 on OSX).

报道,从 Chrome 开发人员工具粘贴的代码可能包含该字符,但我无法使用当前版本(OSX 上的 22.0.1229.79)重现该字符。

How can I spot it?

我怎样才能发现它?

The character is invisible, do how do we know it's there? You can ask your editor to show invisible characters. Most text editors have this feature. Vim, for example, displays them by default, and the ZWSPshows as <u200b>. You can also debug it online: jsbindisplays the character as a red dot on its code panes (but seems to remove it after saving and reloading the page). CodePen.io also displays it as a dot, and keeps it even after saving.

角色是隐形的,我们怎么知道它在那里?您可以要求编辑器显示不可见字符。大多数文本编辑器都有这个功能。例如,Vim 默认显示它们,并且ZWSP显示为<u200b>. 您也可以在线调试它:jsbin在其代码窗格中将字符显示为红点(但似乎在保存并重新加载页面后将其删除)。CodePen.io 还将其显示为 dot,并在保存后保留它。

Related problems

相关问题

That character is not something bad, it can actually be quite useful. This example on Wikipediademonstrates how it can be used to control where a long string should be wrapped to the next line. However, if you are unaware of the character's presence on your markup, it may become a problem. If you have it inside of a string (e.g., the nodeValueof a DOM element that has no visible content), you might expect such string to be empty, when in fact it's not (even after applying String.trim).

这个角色并不是什么坏东西,它实际上非常有用。维基百科上的这个例子演示了如何使用它来控制长字符串应该在哪里换行到下一行。但是,如果您不知道该角色出现在您的标记中,则可能会成为一个问题。如果您将它放在一个字符串中(例如,nodeValue没有可见内容的 DOM 元素的 ),您可能希望这样的字符串为空,而实际上它不是(即使在 apply 之后String.trim)。

ZWSPcan also cause extra whitespace to be displayed on an HTML page, for example when it's found between two <div>elements (as seen on this question). This case is not even reproducible on jsfiddle, since the character is ignored there.

ZWSP也可能导致在 HTML 页面上显示额外的空白,例如当它在两个<div>元素之间找到时(如本问题所示)。这种情况甚至无法在 jsfiddle 上重现,因为在那里忽略了该字符。

Another potential problem: if the web page's encoding is not recognized as UTF-8, the character may actually be displayed (as a?in latin1, for example).

另一个潜在问题:如果网页的编码未被识别为 UTF-8,则该字符可能会实际显示(例如a?在 latin1 中)。

If ZWSPis present on CSS code (inline code, or an external stylesheet), styles can also not be parsed properly, so some styles don't get applied (as seen on this question).

如果ZWSPCSS 代码(内联代码或外部样式表)中存在样式,则样式也无法正确解析,因此某些样式无法应用(如本问题所示)。

The ECMAScript Specification

ECMAScript 规范

I couldn't find any mention to that specific character on the ECMAScript Specification (versions 3and 5.1). The current version mentions similar characters (U+200Cand U+200D) on Section 7.1, which says they should be treated as IdentifierParts when "outside of comments, string literals, and regular expression literals". Those characters may, for example, be part of a variable name (and var x\u200c;indeed works).

我在 ECMAScript 规范(版本35.1)中找不到对该特定字符的任何提及。当前版本在第 7.1 节中提到了类似的字符 ( U+200Cand U+200D) ,其中说当“在注释、字符串文字和正则表达式文字之外”时,它们应该被视为s。例如,这些字符可能是变量名称的一部分(并且确实有效)。IdentifierPartvar x\u200c;

Section 7.2lists the valid White space characters (such as tab, space, no-break space, etc.), and vaguely mentions that any other Unicode “space separator” (category “Zs”) should be treated as white space. I'm probably not the best person to discuss the specs in this regard, but it seems to me that U+200Bshould be considered white space according to that, when in fact the implementations (at least Chrome and Firefox) appear to treat them as an unexpected token (or part of one), causing the syntax error.

第 7.2 节列出了有效的空白字符(如制表符、空格、不间断空格等),并含糊地提到任何其他 Unicode“空格分隔符”(类别“Zs”)都应被视为空白。在这方面,我可能不是讨论规范的最佳人选,但在我看来,U+200B应该将其视为空白,而实际上实现(至少 Chrome 和 Firefox)似乎将它们视为意外令牌(或其中的一部分),导致语法错误。

回答by Nikolay Fominyh

why you looking for this problem into your code? Even, if it's copypasted.

为什么你在你的代码中寻找这个问题?甚至,如果它是复制粘贴的。

If you can see, what exactly happening after save file in synced folder - you will see something like *****at the end of file. It's not related to your code at all.

如果你能看到,在同步文件夹中保存文件后到底发生了什么 - 你会*****在文件末尾看到类似的东西。它根本与您的代码无关。

Solution.

解决方案。

If you are using nginxin vagrant box - add to server config:

如果您nginx在 vagrant box中使用- 添加到服务器配置:

sendfile off;

If you are using apachein vagrant box - add to server config:

如果您apache在 vagrant box中使用- 添加到服务器配置:

EnableSendfile Off;

Source of problem: VirtualBox Bug

问题来源:VirtualBox Bug

回答by Kyle Pennell

This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.

如果您将代码从另一个文档(如 PDF)复制到控制台并尝试运行它,也可能会发生这种情况。

I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.

我试图从我正在阅读的一本 Javascript 书中运行一些示例代码,但很惊讶它没有在控制台中运行。

Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.

显然,从 PDF 复制会在代码中引入一些意外的、非法的和不可见的字符。

回答by user3360944

I had the same problem on my mac and found it was because the Mac was replacing the standard quotes with curly quotes which are illegal javascript characters.

我在我的 mac 上遇到了同样的问题,发现这是因为 Mac 用非法 javascript 字符的卷曲引号替换了标准引号。

To fix this I had to change the settings on my mac System Preferences=>Keyboard=>Text(tab) uncheck use smart quotes and dashes (default was checked).

为了解决这个问题,我不得不更改我的 mac 系统偏好设置=>键盘=>文本(标签)取消选中使用智能引号和破折号(默认被选中)。

回答by Ozzy

I got this error in chrome when I had an unterminated string after the line that the error pointed to. After closing the string the error went away.

当我在错误指向的行之后有一个未终止的字符串时,我在 chrome 中遇到了这个错误。关闭字符串后,错误消失了。

Example with error:

错误示例:

var file = files[i]; // SyntaxError: Unexpected token ILLEGAL

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+');\">Error is here</a>";

Example without error:

没有错误的示例:

var file = files[i]; // No error

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+"');\">Error was here</a>";

回答by msrivas

If you are running a nginx + uwsgi setup vagrant then the main problem is the Virtual box bug with send file as mentioned in some of the answers. However to resolve it you have to disable sendfile in both nginx and uwsgi.

如果您正在运行 nginx + uwsgi setup vagrant,那么主要问题是一些答案中提到的带有发送文件的虚拟框错误。但是要解决它,您必须在 nginx 和 uwsgi 中禁用 sendfile。

  1. In nginx.conf sendfile off

  2. uwsgi application / config --disable-sendfile

  1. 在 nginx.conf 中将 sendfile 关闭

  2. uwsgi 应用程序/配置 --disable-sendfile

回答by Spcaeyob

When running OS X, the filesystem creates hidden forks of basically all your files, if they are on a hard drive that doesn't support HFS+. This can sometimes (happened to me just now) lead to your JavaScript engine tries to run the data-fork instead of the code you intend it to run. When this happens, you will also receive

运行 OS X 时,文件系统会为您的所有文件创建隐藏的分支,如果它们位于不支持 HFS+ 的硬盘驱动器上。这有时(刚才发生在我身上)会导致您的 JavaScript 引擎尝试运行数据叉,而不是您打算运行的代码。发生这种情况时,您还将收到

SyntaxError: Unexpected token ILLEGAL

because the data fork of your file will contain the Unicode U+200B character. Removing the data fork file will make your script run your actual, intended code, instead of a binary data fork of your code.

因为您的文件的数据分支将包含 Unicode U+200B 字符。删除数据分支文件将使您的脚本运行您实际的、预期的代码,而不是代码的二进制数据分支。

.whatever : These files are created on volumes that don't natively support full HFS file characteristics (e.g. ufs volumes, Windows fileshares, etc). When a Mac file is copied to such a volume, its data fork is stored under the file's regular name, and the additional HFS information (resource fork, type & creator codes, etc) is stored in a second file (in AppleDouble format), with a name that starts with ".". (These files are, of course, invisible as far as OS-X is concerned, but not to other OS's; this can sometimes be annoying...)

. 无论如何:这些文件是在本机不支持完整 HFS 文件特征的卷上创建的(例如 ufs 卷、Windows 文件共享等)。当 Mac 文件被复制到这样的卷时,它的数据叉存储在文件的常规名称下,附加的 HFS 信息(资源叉、类型和创建者代码等)存储在第二个文件中(AppleDouble 格式),名称以“.开头。(当然,就 OS-X 而言,这些文件是不可见的,但对于其他操作系统则不可见;这有时会很烦人......)

回答by Miao1007

Here is my reason:

这是我的理由:

before:

前:

var path = "D:\xxx\util.s"

which \uis a escape, I figured it out by using Codepen's analyze JS.

\u是一种逃避,我通过使用Codepen的分析 JS弄清楚了。

after:

后:

var path = "D:\xxx\util.s"

and the error fixed

并修复了错误

回答by rezeli

I am going to add one more answer to the pile. THis problem could happen also because of encoding. You want utf8 encoding to be on safe side. Some editors by default use utf16 which can cause issue. One quick way to test this, is, for example in VS code, simply recreate the same content but use the local editor of vscode to create the file. Hope this helps some.

我要在一堆答案中再添加一个。这个问题也可能因为编码而发生。您希望 utf8 编码处于安全状态。某些编辑器默认使用 utf16,这可能会导致问题。对此进行测试的一种快速方法是,例如在 VS 代码中,只需重新创建相同的内容,但使用 vscode 的本地编辑器来创建文件。希望这对一些人有所帮助。

回答by Erdogan

I changed all space areas to &nbsp, just like that and it worked without problem.

我将所有空间区域更改为  ,就像那样,它可以正常工作。

val.replace(" ", "&nbsp");

val.replace(" ", " ");

I hope it helps someone.

我希望它可以帮助某人。