ES6之解构赋值

简单的记录一下ES6的解构赋值,方便以后查阅。

ES6解构赋值可以在对象和数组中使用。

1、对象的解构赋值

var obj = {
      name: 'Tom',
      age: 15,
      gender: false,
      work: 'teacher',
      hobby: 'basketball'
    }
    var {age} = obj
    console.log(age)

可以看到结果为:15

当然,可以同时赋值给多个变量,如下:

var obj = {
      name: 'Tom',
      age: 15,
      gender: false,
      work: 'teacher',
      hobby: 'basketball'
    }
    var {age,work,hobby} = obj
    console.log(age,work,hobby)

结果为:15 "teacher" "basketball"

可以给变量设置别名,用“:”即可

var obj = {
      name: 'Tom',
      age: 15,
      gender: false,
      work: 'teacher',
      hobby: 'basketball'
    }
    var {age,work,gender:g} = obj
    console.log(age,work,g)

结果为:15 "teacher" false

可以给变量设置默认值,用“=”即可

var obj = {
      name: 'Tom',
      age: 15,
      gender: false,
      work: 'teacher',
      hobby: 'basketball'
    }
    var {age,work,gender:g,ss:s=3} = obj
    console.log(age,work,g,s)

如上所示为同时设置了别名与默认值,结果为:15 "teacher" false 3

如果obj中ss有值,打印出来的是obj中的ss的值

var obj = {
      name: 'Tom',
      age: 15,
      gender: false,
      work: 'teacher',
      hobby: 'basketball',
      ss: 56
    }
    var {age,work,gender:g,ss:s=3} = obj
    console.log(age,work,g,s)

结果为:15 "teacher" false 56

我们也可以使用“...”来获取剩余的值

var obj = {
      name: 'Tom',
      age: 15,
      gender: false,
      work: 'teacher',
      hobby: 'basketball',
      ss: 56
    }
    var {age,work,gender:g,ss:s=3,...r} = obj
    console.log(age,work,g,s,r)

结果为:15 "teacher" false 56 {name: "Tom", hobby: "basketball"}

2.数组的解构赋值

数组的解构赋值与对象的解构赋值相差并不大,需要特别注意的是,数组的解构严格按照数组中的索引来取值,如果取值时想跳过某个值,就需要使用“,”来占位。同样支持设置别名与默认值,也支持“...”获取剩余值

var arr = 'update'.split('')
    var [a,b,,c,...r] = arr
    console.log(arr)
    console.log(a,b,c,r)

结果为:(6) ["u", "p", "d", "a", "t", "e"]
              u p a (2) ["t", "e"]

你可能感兴趣的:(ES6之解构赋值)