Es6 - variable assignment deconstruction

Deconstruction variable assignment

Is defined according to a certain pattern allows ES6, extract from the array and the object values, assignment of the variable, which is called deconstruction.

The first direct assignment

let a = 0;let b = 1;let c = 2;复制代码

The second array structure assigned in the order of one to one

let [d,e,f] = [3,4,5]复制代码

Array pattern to be consistent with the assignment mode

let [d,e,f] = [3,4,5]复制代码

let [d,e,f,[g,h]] = [3,4,5,[6,7]]复制代码

Defaults

let [fun = true] =[];
console.log(fun)   // true复制代码

let [aa,bb = '我是bb'] =['你好'];console.log(aa,bb)    // 你好 我是bb复制代码

let [aa,bb="我是bb"]=['你好',undefined];
console.log(aa,bb)    // 你好 我是bb复制代码

let [aa,bb="我是bb"]=['你好',null];
console.log(aa,bb)    // 你好 null复制代码

undefined is equivalent to nothing, still the default value

It represents null value is null, bb and did not go to a default value, but the structure is null

Object structure assignment key-value pairs like one correspondence.

let {  cc, dd} = {  'cc': '我是cc',  'dd': '我是dd'}console.log(cc, dd)复制代码

Like a key to one correspondence.

corresponds cc cc, dd corresponds dd

Use parentheses

If prior to deconstruct it defines a variable, then this time you deconstruct problems.

let foo;
{foo} ={foo:'圆括号的使用'};
console.log(foo);  报错复制代码

Plus a modification in the statement outside the deconstruction parentheses on it

let foo;
({foo} ={foo:'圆括号的使用'});
console.log(foo);  复制代码

Character string structure string to be deconstructed, this is because, at this time is converted into a string array-like object.

const [a,b,c,d,e,f]="kaikai";
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
console.log(f);复制代码


Reproduced in: https: //juejin.im/post/5d0a0810e51d45590a445b43

Guess you like

Origin blog.csdn.net/weixin_34148340/article/details/93173016