JS解构赋值

2020-04-05  本文已影响0人  又菜又爱分享的小肖

什么是解构?

从一组值中挑出一或多个值,然后把它们分别赋给独立的变量,这也是一个非常常见的需求,举个简单列子

没有使用解构赋值前
//把这个值分别保存在各自的变量中,让他们成为一个独立的变量
    let nextValue=["xxj","tq"];
    let boy=nextValue[0];
    let girl=nextValue[1]
使用后
//用解构赋值,一句话解决上面三句代码
    let [boy,girl]=['xxj','tq']
    alert(boy)//xxj
    alert(girl)//tq
如果你不想取该数组中的全部值
//这样就只会给变量girl赋值,值为tq
    let [, girl]=['xxj','tq']
    alert(girl)//tq
交换两个变量的值,往往都需要第三方变量 列:
 //如何交换两个变量的值?
    let boy='xxj';
    let girl='tq';
    //使用第三方变量
    let temp=boy;
    boy=girl;
    girl=temp;
使用解构后数组赋值,就可以省略掉那个变量temp
    let boy='xxj';
    let girl='tq';
    //使用解构赋值,就不需要第三方变量,就解决了第三方变量的繁琐
    let [boy,girl]=['tq','xxj']
对象解构赋值
    let person={
        name:'xxj',
        age:20
    }
    //使用解构后,相当于给name,age取了个别名,就是外号的意思,比如周树人:鲁迅
    let {name:personName,age:personAge}=person
    alert(personName)//xxj
    alert(personAge)//20
数组解构
        let arr=[1,2,3,4,5,6]
        let arr2=[7,8,9,10]
        let arr3=[...arr,...arr2]
        //可以说是把arr和arr2中的数值,push到arr3中
        console.log(arr3)//[1,2,3,4,5,6,7,8,9,10]
默认值

在数组的结构赋值表达式中也可以为数组的任意位置添加默认值,当指定位置的属性不存在或其值为undefind时使用该默认值

        let list=[123,'xxj'];
        //如果city属性为undefind时,取该默认值深圳
        let [num,peron,city='深圳']=list
        console.log(num,person,city)//123,xxj,深圳
不定元素赋值

在数组中,可以通过...语法将数组中其余的元素赋值给一个特定的变量,列:

       let colors=['red','green','blue']
       let [firstColor,...othersColor]=colors
       console.log(firstColor)//red
       console.log(othersColor)//['green','blue']
上一篇 下一篇

猜你喜欢

热点阅读