search

Home  >  Q&A  >  body text

Square bracket notation for JavaScript objects: using assignment on the left ({ Navigation } =)

<p>I haven't seen this syntax before and would like to know what it means. </p> <pre class="brush:php;toolbar:false;">var { Navigation } = require('react-router');</pre> The curly brace on the left of <p> will cause a syntax error: </p> <blockquote> <p>unexpected token {</p> </blockquote> <p>I'm not sure which part of the webpack configuration does the conversion, or what the purpose of this syntax is. Is this a Harmony thing? Can someone explain this to me? </p>
P粉964682904P粉964682904466 days ago415

reply all(2)I'll reply

  • P粉578343994

    P粉5783439942023-08-25 10:55:29

    This is destructuring assignment. It is a new feature of ECMAScript 2015.

    var {
      AppRegistry,
      StyleSheet,
      Text,
      View,
    } = React;

    Equivalent to:

    var AppRegistry = React.AppRegistry;
    var StyleSheet = React.StyleSheet;
    var Text = React.Text;
    var View = React.View;

    reply
    0
  • P粉350036783

    P粉3500367832023-08-25 10:49:56

    It is called Destructuring assignment and is part of the ES2015 standard .

    Object destructuring

    var o = {p: 42, q: true};
     var {p, q} = o;
    
     console.log(p); // 42
     console.log(q); // true 
    
     // 分配新的变量名
     var {p: foo, q: bar} = o;
    
     console.log(foo); // 42
     console.log(bar); // true

    Array destructuring

    var foo = ["one", "two", "three"];
    
    // 不使用解构
    var one   = foo[0];
    var two   = foo[1];
    var three = foo[2];
    
    // 使用解构
    var [one, two, three] = foo;

    reply
    0
  • Cancelreply