当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ES6 对象的解构赋值

ES6 对象的解构赋值

2020年03月25日  | 移动技术网IT编程  | 我要评论

对象是无序的,必须使用属性名去匹配

因此解构赋值时变量名必须与对象的属性名保持一致

const obj={
    a:1,
    b:2
};
let {a,b}=obj;

 

 

 

比较复杂的结构条件:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>demo</title>
</head>
<body>
<script>

const person={
    name:"cyy",
    age:10,
    friends:[{
        name:"cyy2",
        age:20
    },{
        name:"cyy3",
        age:30
    },{
        name:"cyy4",
        age:40
    }]
};

const {name}=person;//name   "cyy"
const {age}=person;//age   10

//只能取到friend1,不能取到friends
const {friends:[friend1]}=person;//friend1   {name: "cyy2", age: 20}
const {friends:[,friend2]}=person;//friend2   {name: "cyy3", age: 30}
const {friends:[,,friend3]}=person;//friend3   {name: "cyy4", age: 40}

const {friends:[{name}]}=person;//name   "cyy2"
const {friends:[,{age}]}=person;//age   30
const {friends:[{name},{name},{name}]}=person;
</script>
</body>
</html>

如果出现对象属性名重复的情况,会报错

 

 

 

解决方法是使用: 来定义别名

const {friends:[{name:fname1},{name:fname2},{name:fname3}]}=person;// "cyy2"  

 

 

 

对象的解构赋值结合扩展运算符:

const obj={
    name:"cyy",
    age:18,
    id:1
}

const {name,...oth}=obj;

 

 

 

使用扩展运算符合并对象:

const obj1={
    name1:"cyy1",
    age1:18
}
const obj2={
    name2:"cyy2",
    age2:28
}
const obj3={
    name3:"cyy3",
    age3:38
}
const obj={
    name:"cyy",
    ...obj1,
    ...obj2,
    ...obj3
}

 

 

 

如何对已经声明的变量进行对象的解构赋值:

let person;//声明变量
const p={
    name:"cyy",
    age:18
}
{person}=p;

这种情况下会报错,因为把{person}看成了一个块级作用域

 

 

解决方法是外面用圆括号包裹

let person;//声明变量
const p={
    name:"cyy",
    age:18
};

({person}=p);

居然没有获取到数据,尴尬……

 

 

总而言之不建议先声明再结构赋值哈,最好是声明的同时进行解构赋值

 

默认值:

当属性值不存在或者为undefined时,会使用默认值

const person={
    name:"cyy",
    age:18
};

let {name,age=20,hobby=["html","css"]}=person;

 

 

对象的解构赋值常用场景:

提取对象属性

const {name,hobby:[hobby1]}={
    name:"cyy",
    age:18,
    hobby:[
        "html",
        "css"
    ]
}

 

 

需要注意的是,这样是拿不到hobby的值,如果需要获取hobby,则需要单独再加

const {name,hobby:[hobby1],hobby}={
    name:"cyy",
    age:18,
    hobby:[
        "html",
        "css"
    ]
}

 

 

使用对象传入乱序的函数参数:

function ajax({
    url,
    data,
    type="get"
}){
    console.log(type);
}

ajax({
    //可以乱序
    url:"getxxx",
    data:{
        a:1
    }
})

 

 

获取多个 函数返回值

function getinfo(uid){
    //...
    
    return {
        status:"success",
        data:{
            a:1
        },
        info:"hello"
    }
}

const {status,data,info}=getinfo(333);

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网