ES6 2.解构赋值

2018-07-19  本文已影响0人  Coldhands

解构赋值

解构赋值的分类

1.数组解构赋值

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

输出结果:1 2

{
    let a,b,rest;
    [a,b,...rest] = [1,2,3,4,5,6];
    console.log(a,b,rest);
}

输出结果:1 2 [3,4,5,6]

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

输出结果:1 2 undefined

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

输出结果:1 2 3

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

输出结果:2 1

{
    function f(){
        return [1,2];
    }
    let a,b;
    [a,b] = f();
    console.log(a,b);
}

输出结果:1 2

{
    function f(){
        return [1,2,3,4,5];
    }
    let a,b;
    [a,,,b] = f();
    console.log(a,b);
}

输出结果:1 4

{
    function f(){
        return [1,2,3,4,5];
    }
    let a,b;
    [a,,...b] = f();
    console.log(a,b);
}

输出结果:1 [3,4,5]
2.对象解构赋值(左侧和右侧都要是对象的格式)

{
    let a,b,rest;
    ({a,b} = {a: 1, b: 2});
    console.log(a,b);
}

输出结果:1 2

{
    let o = {p:12, q:true};
    let {p,q} = o;
    console.log(p,q);
}

输出结果:12 true

{
    let {a=10, b=5} = {a: 3};
    console.log(a,b);
}

输出结果:3 5

{
    let metaData = {
        title: 'binbin',
        content: [{
            title: 'yueyue',
            time: '2015-01-01'
        }]
    }
    let {title: a, content:[{title: b}]} = metaData;
    console.log(a,b);
}

输出结果:binbin yueyue

上一篇下一篇

猜你喜欢

热点阅读