在控制台中定义一个JavaScript对象 [英] Defining a JavaScript object in console
问题描述
> true $ b $在Chrome JavaScript Console中输入简单对象时,我得到如下输出: b true
> 1/3
0.3333333333333333
等等。
但是当我输入对象时会出现语法错误:
> {a:1,b:2}
语法错误:意外的标记:
arguments:Array [1]
0::
长度:1
__proto__:数组[0]
获取消息:函数getter(){[native code]}
get stack:function getter(){[native code]}
set message:function setter(){ [native code]}
set stack:function setter(){[native code]}
type:unexpected_token
__proto__:错误
虽然我确信这个表达式可以在初始化对象时正确使用,因为:
<$
$ b $ 2
__proto__对象
也许这是一个sil但是我真的很想知道为什么会发生这种情况?
因为您的语句被评估为<而不是对象字面声明。 p>
请注意,ExpressionStatement不能以开头大括号开头,因为这可能会使其与块不明确。此外,ExpressionStatement不能以function关键字开头,因为这可能会使它与FunctionDeclaration模糊不清。
为了使其评估为表达式时,它必须是一个赋值的右边,用圆括号包围或在运算符前面。 (!{a:1,b:2}
)
When I type simple objects to Chrome JavaScript Console, I get an output like this:
>true
true
>1/3
0.3333333333333333
And so on.
But a syntax error occurs when I type objects:
>{ a: 1, b: 2 }
SyntaxError: Unexpected token :
arguments: Array[1]
0: ":"
length: 1
__proto__: Array[0]
get message: function getter() { [native code] }
get stack: function getter() { [native code] }
set message: function setter() { [native code] }
set stack: function setter() { [native code] }
type: "unexpected_token"
__proto__: Error
While I know for sure that this expression could be correctly used in initializing an object, because:
>obj = { a: 1, b: 2 }
Object
a: 1
b: 2
__proto__: Object
Maybe it's a silly question, but I really want to know the reason why is this happening?
Because your statement is being evaluated as a block, not an object literal declaration.
Note that an ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.
To make it evaluate as an expression, it needs to be the right-hand side of an assignment, wrapped in parentheses or preceded by an operator. (!{a:1,b:2}
)
这篇关于在控制台中定义一个JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!