Destructuring

Destructuring is a way to quickly extract data out of an {} or [] withouthaving to write much code.

To borrow from the MDN, destructuring can be used to turn thefollowing:

  1. let foo = ['one', 'two', 'three'];
  2. let one = foo[0];
  3. let two = foo[1];
  4. let three = foo[2];

into

  1. let foo = ['one', 'two', 'three'];
  2. let [one, two, three] = foo;
  3. console.log(one); // 'one'

This is pretty interesting, but at first it might be hard to see the use case.ES6 also supports object destructuring, which might make uses more obvious:

  1. let myModule = {
  2. drawSquare: function drawSquare(length) { /* implementation */ },
  3. drawCircle: function drawCircle(radius) { /* implementation */ },
  4. drawText: function drawText(text) { /* implementation */ },
  5. };
  6. let {drawSquare, drawText} = myModule;
  7. drawSquare(5);
  8. drawText('hello');

Destructuring can also be used for passing objects into a function, allowing you to pull specific properties out of an object in a concise manner. It is also possible to assign default values to destructured arguments, which can be a useful pattern if passing in a configuration object.

  1. let jane = { firstName: 'Jane', lastName: 'Doe'};
  2. let john = { firstName: 'John', lastName: 'Doe', middleName: 'Smith' }
  3. function sayName({firstName, lastName, middleName = 'N/A'}) {
  4. console.log(`Hello ${firstName} ${middleName} ${lastName}`)
  5. }
  6. sayName(jane) // -> Hello Jane N/A Doe
  7. sayName(john) // -> Helo John Smith Doe

There are many more sophisticated things that can be done with destructuring,and the MDN has some great examples, including nested objectdestructuring and dynamic destructuring with for … in operators".

原文: https://angular-2-training-book.rangle.io/handout/features/destructuring.html