es6结构赋值(3篇)

es6结构赋值:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>es6结构赋值</title>
</head>
<body>

    <script>
        //es6结构赋值
        let arr=["held","word","good"];
        let [firstname,twoname] =  arr
        console.log(firstname,twoname); //held word


        let demo = ["a","b","c","d"];
        let [name1, , name3] = demo;
        console.log(name1,name3);//a c


        //属性赋值
        let user = {name:"张三",old:"18"};
        [user.name,user.old] = [1,2]
        console.log(user);//{name: 1, old: 2}

    </script>
    
</body>
</html>

 数组结构赋值

<script>
        //数组结构赋值
        let arr = [ 1,2,3,4,5,6,7,8,9]
        let [firstname,curname,...last] = arr
        console.log(firstname,curname,last);//1 2 (7) [3, 4, 5, 6, 7, 8, 9]
    </script>

 对象结构赋值

<script>
        //object结构赋值
        let options = {
            title:"menu",
            100,
            heigth:100
        }
        //左边是变量右边是赋值
        let {title,width,heigth} = options;
        console.log(title,width,heigth)//menu 100 100
    </script>

 对象结构赋值2

<script>
        //object结构赋值
        let options = {
            title:"menu",
            heigth:100
        }
        //默认值
        let {title:title2,width=130,heigth} = options;
        console.log(title2,width,heigth)//menu 130 100
    </script>

对象结构赋值 3

<script>
        //object结构赋值
        let options = {
            title:"menu",
            100,
            heigth:100
        }
        //...last
        let {title,...last} = options;
        console.log(title,last)//menu { 100, heigth: 100}
    </script>

对象结构嵌套赋值

<script>
        //object结构嵌套赋值
        let options = {
            size:{
                100,
                heigth:200
            },
            items:['cake','donut'],
            heigth:100
        }
        let {size:{width}} = options;
        console.log(width)//100
    </script>

 对象结构嵌套赋值2

<script>
        //object结构嵌套赋值
        let options = {
            size:{
                100,
                heigth:200
            },
            items:['cake','donut'],
            heigth:100
        }
        let {size:{kuan,heigth},items:[item1]} = options;
        console.log(kuan,heigth,item1)//100 200 "cake"
    </script>
原文地址:https://www.cnblogs.com/huanghuali/p/13019126.html