变量的解构赋值

如何理解解构

允许按照一定的方式将对象或者数组提取出来赋值到对应的变量上

数组解构

注意:数组解构是按顺序的解构
let [a, b, c] = [1, 2, 3]  //左右相同
//a = 1 
//b = 2 
//c = 3

let [a] = [1, 2]  // 左边少,右边多
//a = 1

let [a, b] = [1] //右边少,左边多
//a = 1
//b = undefined
let [a = 2] = [] //如果结构后结果为undefined则为默认值
//a = 2

注意:只有当解构后的值严格等于undefined( === undefined)默认值才生效,如下情况
let [x = 1] = [undefined] // x = 1
let [x = 1] = [null] // x = null

小知识: 
undefined == null // true     
undefined === null // false
//当默认值为函数时会惰性求值
function foo(){
    console.log('called')
    return 2;
}

let [x = foo()] = [1]
> x 
< 1

let [x = foo()] = []  //解构后的值为undefined,执行foo函数
< called
> x
< 2

对象解构

{模式: 变量} = {对象}
{name: name, age: age} = {name: 'colin', age: 2} ->(简写) let {name, age} = {name: 'colin', age: 2} 
//name = 'colin'
//age = 2

注意:对象解构变量名必须与属性同名才能取到正确的值
let {addr} = {name: 'colin', age: 2}
//addr = undefined

灵活用法:
let {log, sin, cos} = Math  //将Math中的三个函数解构出来

actions: { //在vuex中actions中的函数会携带context参数,我们可以使用对象解构将需要用到的函数提取出来
  increment ({ commit }) {
    commit('increment')
  }
}


默认值
let {x = 3} = {}
// x = 3
let {x, y = 5} = {x: 1}
// x = 1
// y = 5

注意:对象默认值的生效条件与数组一样,即对象的属性值严格等于undefined ( === undefined)
let {x = 3} = {x : undefined} // x = 3
let {x = 3} = {x : null} // x = null

字符串解构

const [a,b,c,d,e] = 'hello'
//a = 'h'
//b = 'e'
//c = 'l'
//d = 'l'
//e = 'o'

let {length : len} = 'hello'
//len = 5

数值和布尔值的解构

注意:对数值和布尔值进行解构时会先将其转为对象
let {toString : s} = 123
let {toString : s} = true
由于数值和布尔值的对象都有toString方法所以会将其toString方法提取出来
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值