why are objects wrapped in parenthesis in JS?

后端 未结 3 1117
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 00:57

Given the following example:

var foo = {
    root:
        ({
            key1: \"Value1\",
            key2: \"Value2\",
            key3: \"Value3\"
               


        
3条回答
  •  独厮守ぢ
    2020-12-17 01:23

    As per me, we should use square brackets to collect the objects. because, JavaScript will understand that it is an array.

    Round brackets(used in example 1) are just validated by the javasript parser. When you try to access it, java script returns Only last object in the round brackets(like top object in the stack).

    Try below script

    var foo = {
        root1:
            {
                key1: "Value1",
                key2: "Value2",
                key3: "Value3"
            },
        root2:({
                key4: "Value4",
                key5: "Value5"
              },{
                key6: "Value6",
                key7: "Value7"
            }),
        root3:[
             {
                key8: "Value8",
                key9: "Value9"
              },{
                key10: "Value10",
                key11: "Value11"
              }
        ]
        };
        console.log(foo['root1']);  // returns object { key1, key2, key3}
        console.log(foo['root2']);  // returns only { key6,key7}
        console.log(foo['root3']);  //returns [ {key8,key9},{key10,key11}]
    

提交回复
热议问题