解构赋值使用场景

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es6</title>
</head>
<body>
<script>
// 变量交换
{
    let a = 1;
    let b = 2;
    [a, b] = [b, a];
}

// 多个返回值
{
    function f() {
        return [1, 2];
    }
    let a, b;
    [a, b] = f();
}

//返回多个值,只关心想要的
{
    function f() {
        return [1, 2, 3, 4, 5];
    }
    let a, b;
    [a,,,b] = f();
}

//返回多个值,不知道返回的长度
{
    function f() {
        return [1, 2, 3, 4, 5];
    }
    let a, b;
    [a,...b] = f();
}

//对象的解构赋值(key值要一样)
{
    let o = {p: 2, q: true};
    let {p, q} = o;
    console.log(p, q);
    //2 true
}

//对象的默认值
{
    let {a = 3, b = 5} = {a: 3};
    console.log(a, b);
    //3 5
}

//json解构,key值必须一样,value可以自己取名
{
    let metaData = {
        title: 'abc',
        test: [{
            title: 'test',
            desc: 'description'
        }]
    }
    let {title: esTitle, test: [{title: cnTitel}]} = metaData;
    console.log(esTitle, cnTitel);
    //abc test
}
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_41900808/article/details/88539270