微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ES6结构赋值

// 解构赋值

        // 1.数组
        var a, b, c
        [a, b, c] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        console.log(a, b, c);// 1 , 2 , 3
        [d, e, ...f] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        console.log(d, e, f); // 1  2  3-9
        // 函数返回数组结构
        function arrreturn() {
            return [10, 20, 30, 40]
        }
        [arritem1, arritem2, arritem3, arritem4] = arrreturn()
        console.log(arritem1, arritem2, arritem3, arritem4); //10 20 30 40
        // 解构赋值数组的认值
        [defa1 = 1, defa2 = 2, defa3 = 3] = [10]
        console.log(defa1, defa2, defa3); //10 2 3 可以使用等于号进行设置认值,如果有解构赋的值,那么认值不生效



        // 2.对象
        ({ name, age } = { name: '张三', age: 25 })
        console.log(name, age); //张三  25

        ({ name, age, ...surplus } = { age: 25, name: '李四', color: 'yellow', fruits: 'apple' })
        console.log(name, age, surplus);//李四 25 {color: 'yellow', fruits: 'apple'}

        var obj = { obja: 1, objb: 2 }
        var { obja: objaContent, objb: objbContent } = obj
        console.log(objaContent, objbContent);  //1 2


        // for of 迭代解构
        var people = [
            {
                name: 'Mike Smith',
                family: {
                    mother: 'Jane Smith',
                    father: 'Harry Smith',
                    sister: 'Samantha Smith'
                },
                age: 35
            },
            {
                name: 'Tom Jones',
                family: {
                    mother: 'norah Jones',
                    father: 'Richard Jones',
                    brother: 'Howard Jones'
                },
                age: 25
            }
        ];
        for(var {name:n,family:{mother:m,father:f}} of people){
            console.log('my:'+n,'mother:'+m,'father:'+f);
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐