What difference does it makes to parse something as an object literal rather than as a block?

前端 未结 2 1233
刺人心
刺人心 2021-01-28 23:51

Sorry for my ignorance on JavaScript basic concepts.

It boils down to this:

Literal - A value found directly in the script. Examples:

2条回答
  •  悲哀的现实
    2021-01-29 00:25

    First, don't eval JSON, use JSON.parse on the String source


    A block is a "group of expressions" for example,

    let x = 0;
    if (true) {
        // this is a block
        ++x;
    }
    

    However, equally this is also a block

    let x = 0;
    { // hi there, I'm a block!
        ++x;
    }
    

    This means when the interpreter sees block notation, it assumes a block even if you do something like this

    { // this is treated as a block
        foo: ++x
    }
    

    Here, foo acts as a label rather than a property name and if you try to do more complex things with the attempted object literal, you're going to get a Syntax Error.

    When you want to write an Object literal ambiguously like this, the solution is to force the interpreter into "expression mode" explicitly by providing parenthesis

    ({ // this is definately an Object literal
        foo: ++x
    })
    

提交回复
热议问题