ES6 study notes deconstruction assignment

1. array assignment deconstruction

Simple usage

{
    // 旧
    let a=1,b=3;

    //新
    let [a,b]=[1,3];

    console.log(a,b);// 1 3
}

As long as the same pattern on both sides of the equal sign, the variable on the left will be given corresponding values.

{
     let a,b,c;
     [a,b,c]=[1,2]
     console.log(a,b,c);// 1 2 undifined
}

{
    let [a,b,c]=[1,,3];
    a,b,c;//1 undefined 3
}

{
    let [a,b]=[1,[2,3]];
    a;//1
    b;//[2,3]
}

{
    let [a,...b]=[1,2,3];
    a;//1
    b;//[2,3]
}

{
    let [a, b, ...c] = [1];
    a;//1
    b;//undefined
    c;//[]
}

{
    let [a,[b],c]=[1,[2,3],4]
    a;//1
    b;//2
    c;//4
}

Set Default

let [a='hello']=[];
a;//hello

let [b='world']=['yes'];
b;//yes

// ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效。
let [c=13]=[undefined];
c;//13

let [d=12]=[null];
d;//null

Examples

  • Exchange of the value of two variables
    let [a, b]=[2,3];
    [a,b]=[b,a];
    console.log(a);//3

Deconstruction object

General usage

    let a,b;
    ({ a, b } = { a: 2, b: 3 })
    console.log(a,b);//2,3;

    //变量名与属性名一致
    let {name}={name:'小明',age:18};
    console.log(name);//小明

    // 变量名与属性名不一致
    let {a:name,b:age}={a:'小明',b:18};
    console.log(name,age);//小明 18

If deconstruction fails, the value of the variable is equal to undefined.

let {a}={b:2};
a;//undefined

Nested

function fn() {
    return {
        name: '小明',
        userList: [
            { name: '小红' }
        ]
    }
}

let res = fn();
let { name: person, userList: [{ name: otherPerson }] } = res;

console.log(person, otherPerson);//小明 小红

If deconstruction mode is nested objects, attributes and parent child object resides does not exist, will be thrown.

let {a: {b}} = {b: 666};

Set Default

let {a=1}={a:3};

Guess you like

Origin www.cnblogs.com/roseAT/p/11444112.html