{}.toString() 未捕获的语法错误:意外的令牌 [英] {}.toString() Uncaught SyntaxError: Unexpected token
问题描述
当我在 chrome 开发工具中尝试时,它显示Uncaught SyntaxError: Unexpected token .
但是,如果它分配给a:
when I try it in chrome dev tools, it shows
Uncaught SyntaxError: Unexpected token .
However if when it assign to a:
var a={}.toString();
a //[object Object]
是什么导致了差异?
推荐答案
是什么导致了差异?
what caused the difference?
解析器所处的状态.默认情况下,解析器处于期望语句的状态.因此,在控制台中的示例中, {
看起来像是对它的块的打开,而不是对象初始值设定项的开始.(此时你也可以给它一个表达式,因为 JavaScript 有 ExpressionStatement 的概念,它是一个完全由表达式组成的语句.)
The state the parser is in. By default, the parser is in a state where it expects a statement. So in your example in the console, the {
looks like the opening of a block to it, not the beginning of an object initializer. (You can also give it an expression at that point, because JavaScript has the concept of the ExpressionStatement, which is a statement consisting entirely of an expression.)
但是在您的 var a={}.toString();
代码中,{}.toString()
出现在赋值的右侧,解析器需要一个表达式,而不是一个语句.所以 {
启动一个对象初始值设定项.
But in your var a={}.toString();
code, the {}.toString()
appears on the right-hand side of an assigment, where the parser is expecting an expression, not a statement. So the {
starts an object initializer.
如果你做一些事情让解析器期待一个表达式,它也可以在控制台中工作:
If you do something to make the parser expect an expression instead, it'll work in the console too:
({}).toString(); // "[object Object]"
或
+{}.toString(); // NaN, because the `+` tries to turn `[object Object]` into a number and fails
这篇关于{}.toString() 未捕获的语法错误:意外的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!