美文网首页
ES6 2.解构赋值

ES6 2.解构赋值

作者: Coldhands | 来源:发表于2018-07-19 00:01 被阅读0次

解构赋值

解构赋值的分类
  • 数组解构赋值
  • 对象解构赋值
  • 字符串解构赋值
  • 布尔值解构赋值
  • 函数参数解构赋值
  • 数值解构赋值

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

相关文章

网友评论

      本文标题:ES6 2.解构赋值

      本文链接:https://www.haomeiwen.com/subject/bziapftx.html