[ES6] variable assignment deconstruction

Deconstruction: ES6 allows assignment of variables from the data objects and extracting a pattern in accordance with the value of

1. array assignment deconstruction

let [a, b, c] = [1, 2, 3];
let [x, , y] = [1, 2, 3];
x // 1
and // 3

If unsuccessful deconstruct the value of the variable is equal toundefined

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
from // []

Incomplete deconstruction , namely the equal sign to the left of the mode, only an array of matching the right part of the equal sign

let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

If the right of the equal sign can not traverse the deconstruction (itself does not have the Iterator interface), then the error will

Defaults

Deconstruction assignment allows you to specify a default value.

Note that, for ES6 internal strict equality operator ( ===), it is determined whether there is a location value. Therefore, only when strictly equal member of an array undefined, the default values to take effect.

let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

2. Object deconstruction assignment

let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

Actually

let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };

fooPattern matching, bazis variable. Truly assignment is a variable baz, rather than a model foo.

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined

 Defaults

The default value of the entry into force of the conditions is that object's property value exactly equal undefined.

var {x = 3} = {x: undefined};
x // 3

var {x = 3} = {x: null};
x // null

important point

 

Guess you like

Origin www.cnblogs.com/Mijiujs/p/12084309.html