为什么以“-->”开头的行不会在 Javascript 中引发错误?
Why does a line starting with "-->" not throw an error in Javascript?
考虑以下三行 Javascript.
console.log(1);
--> console.log(2);
console.log(3);
我预计它会导致 Syntax Error
,可能类似于 Unexpected token --
。
相反,浏览器似乎接受代码,并简单地忽略第二行,产生输出:
› 1
› 3
我已尝试将代码段粘贴到 Chrome、Safari 和 Firefox 的控制台中。他们都以同样的方式行事。怎么回事?
这是针对旧版浏览器的 HTML 评论的一部分,其模式在不支持 <script>
标签的浏览器中具有 Javascript 部分。
<script>
<!--
// some code
-->
</script>
摆弄控制台似乎证明了 Nina 的情况
-->
undefined
typeof -->
Uncaught SyntaxError: Unexpected token >
--> = "foo"
undefined
-->
undefined
--<
Uncaught SyntaxError: Unexpected token <
<--
Uncaught SyntaxError: Unexpected token <
<!--
undefined
<!-- foo -->
undefined
这些关键字似乎总是设置为 return 未定义。
显然 ECMAScript 官方允许 "HTML like" comments:
B.1.3 HTML-like Comments
The syntax and semantics of 11.4 is extended as follows except that this extension is not allowed when parsing source code using the goal symbol Module:
HTMLCloseComment::
WhiteSpaceSequence opt SingleLineDelimitedCommentSequence opt --> SingleLineCommentChars opt
这表明 -->
之后的任何内容都应视为注释。
考虑以下三行 Javascript.
console.log(1);
--> console.log(2);
console.log(3);
我预计它会导致 Syntax Error
,可能类似于 Unexpected token --
。
相反,浏览器似乎接受代码,并简单地忽略第二行,产生输出:
› 1
› 3
我已尝试将代码段粘贴到 Chrome、Safari 和 Firefox 的控制台中。他们都以同样的方式行事。怎么回事?
这是针对旧版浏览器的 HTML 评论的一部分,其模式在不支持 <script>
标签的浏览器中具有 Javascript 部分。
<script>
<!--
// some code
-->
</script>
摆弄控制台似乎证明了 Nina 的情况
-->
undefined
typeof -->
Uncaught SyntaxError: Unexpected token >
--> = "foo"
undefined
-->
undefined
--<
Uncaught SyntaxError: Unexpected token <
<--
Uncaught SyntaxError: Unexpected token <
<!--
undefined
<!-- foo -->
undefined
这些关键字似乎总是设置为 return 未定义。
显然 ECMAScript 官方允许 "HTML like" comments:
B.1.3 HTML-like Comments
The syntax and semantics of 11.4 is extended as follows except that this extension is not allowed when parsing source code using the goal symbol Module:
HTMLCloseComment::
WhiteSpaceSequence opt SingleLineDelimitedCommentSequence opt --> SingleLineCommentChars opt
这表明 -->
之后的任何内容都应视为注释。