Destructuring:
数组:
let [firstValue] = [1]; // firstValue: 1
let c, d;
let [a, b] = [c, d] = [1, 2];
var [head, ...tail] = [1, 2, 3, 4]; // tail: [2,3,4]
可以交换变量:
let [x, y] = [‘ax‘, ‘why‘];
[x, y] = [y, x]; // x: why, y:ax
const all = [‘ax‘, ‘why‘, ‘zet‘];
const [,,z] = all; // z: set
嵌套数组也可以:
const user = [[‘Some‘, ‘One‘], 23];
const [[firstName, surname], age] = user;
for (var [a, b] of [[1, 2]]) {} // a:1, b:2
字符串也可以哦:
let [a, b, c] = ‘abc‘; // [a, b, c]: [‘a‘, ‘b‘, ‘c‘]
object:
const {t: x} = {t: 1, b:2}; // x:1
const {x} = {x: 1, b:2}; // x:1
const m = {first: 23, second: 42};
const {magic: {second: second}} = {magic: m}; // second: 42
const {z:[,x]} = {z: [23, 42]}; // x:42
const [,[{lang: lang}]] = [null, [{env: ‘browser‘, lang: ‘ES6‘}]]; // lang: es6
包括prototype:
const {substr} = "1"; // substr: String.prototype.subst
默认值:
const [,b=2] = [1,,3]; // b:2
const {a, b=2} = {a: 1, b: undefined}; // b:2
const {a, b=2} = {a: 1};
const {x: y=42} = {y: 23}; // y: 42
参数处理:
const fn = ({id, name}) => {
// ...
};
const user = {name: ‘Wolfram‘, id: 42};
fn(user); // id: 42, name: Wolfram
const fn = ([,{name}]) => {
// ...
};
const users = [{name: ‘nobody‘}, {name: ‘Alice‘, id: 42}];
fn(users); // name: alice
同样可以使用默认值:
const fn = (id, name=‘Bob‘, c) => {
// ...
};
fn(23, undefined, 3); // id:23, name: Bob, c:3
const fn = (id, name=‘Bobby‘) => {
// ...
};
fn(23, ‘Bob‘); // id:23, name: Bob
const defaultUser = {id: 23, name: ‘Joe‘};
const fn = ([user=defaultUser]) => {
// ...
};
fn([]); // user: defaultUser
const fn = (id=1, [arr], {obj=2}) => {
// ...
};
fn(void 0, [2], {obj:3}); // id: 1, arr: 2, obj: 3