如何理解解构
允许按照一定的方式将对象或者数组提取出来赋值到对应的变量上
数组解构
注意:数组解构是按顺序的解构
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方法提取出来