Object destructuring syntax - ES6

前端 未结 2 994
臣服心动
臣服心动 2021-01-17 06:21

I had been through array destructuring syntax, which is well understood.

What exactly are we doing below, when we say var {p, q} = o;?

Is

2条回答
  •  死守一世寂寞
    2021-01-17 06:54

        var o = {p: 42, q: true};
         var {p, q} = o;
    

    Here, var {p,q} = o is just a shorthand for var {p:p , q:q} = o

    Consider this.

          var o = { key : "value" };
          var { key : local_var } = o ;
          local_var === o["key"] // true
    

    If you omit the local_var, and write var {key} = o; a new variable key will be created with the idenifier "key"., same like doing var key = o["key"]

    So in your example that's like doing

          var p =  o["p"] ;  //42
           var q = o["q"];   //true
           var a = o["a"];  // undefined
           var b = o["b"];   //undefined
    

    This may not be exactly true, but should help you understand it.
    It's kind of something like Pattern Matching that other languages provide, but it's different.

提交回复
热议问题