Defining a JavaScript object in console

后端 未结 6 503
夕颜
夕颜 2020-12-18 04:18

When I type simple objects to Chrome JavaScript Console, I get an output like this:

>true
true
>1/3
0.3333333333333333

And so on.

相关标签:
6条回答
  • 2020-12-18 04:45

    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})

    0 讨论(0)
  • 2020-12-18 04:52
     { a: 1, b: 2 }
    

    is a code block, with two wrongly labelled variables.

    To create an object, surround the code block by parentheses, so that the braces are interpreted as object literals:

    ({ a: 1, b: 2 })
    
    0 讨论(0)
  • 2020-12-18 04:58

    Try this instead:

    ({ "a" : 1, "b" : 2 })
    
    0 讨论(0)
  • 2020-12-18 04:59

    Because your statement is being evaluated as a block, not an object literal declaration.

    True josh

    If you want it to be evaluated as an object, just write :

    > ({a : 1, b : 2})
    Object
    a: 1
    b: 2
    __proto__: Object
    
    0 讨论(0)
  • 2020-12-18 05:03

    Because { a: 1, b: 2 } is not a valid expression to execute. JavaScript looks it like a block of code since it starts and ends to curly braces.

    If you try ({ a: 1, b: 2 }), it will work.

    0 讨论(0)
  • 2020-12-18 05:04

    It's because an opening { with no context is interpreted as the beginning of a block. You can use parentheses:

    ({ a: 1, b: 2 })
    

    As it is though, it's just a block of execution - like one might find after an if or for. So you can type:

    {alert("Hello!");}
    

    Here's more about that. Blocks sort of return values too, which is both awesome and disappointing.

    0 讨论(0)
提交回复
热议问题