Javascript object bracket notation ({ Navigation } =) on left side of assign

后端 未结 4 778
梦谈多话
梦谈多话 2020-11-21 05:53

I haven\'t seen this syntax before and am wondering what it\'s all about.

var { Navigation } = require(\'react-router\');

The brackets on

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 06:36

    It's called destructuring assignment and it's part of the ES2015 standard.

    The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

    Source: Destructuring assignment reference on MDN

    Object destructuring

     var o = {p: 42, q: true};
     var {p, q} = o;
    
     console.log(p); // 42
     console.log(q); // true 
    
     // Assign new variable names
     var {p: foo, q: bar} = o;
    
     console.log(foo); // 42
     console.log(bar); // true
    

    Array destructuring

    var foo = ["one", "two", "three"];
    
    // without destructuring
    var one   = foo[0];
    var two   = foo[1];
    var three = foo[2];
    
    // with destructuring
    var [one, two, three] = foo;
    

提交回复
热议问题