概念:他是一种针对数组或者对象进行模式匹配,然后对其中的变量进行赋值。方便了复杂对象中数据字段获取。
适用场景:
获取store / localStorage / sessionStorage等存的对象中的属性;
获取复杂函数中的多个返回值(js函数是对象);
接口返回参数转换;
1.对象中的属性
const name = this.item.name
const id = this.item.id
const url = this.item.url
// 简写如下
const { name, id, url } = this.item
2.取值函数中返回的值
import { personalSave } from '@/composition/personaloffice'
const scrollPositionNumber = personalSave().saveLandInfo
const onScrollToPosition = personalSave().saveSeaInfo
//简写如下
import { personalSave } from '@/composition/personaloffice'
const { saveLandInfo, saveSeaInfo} = personalSave()
3. 数组中的解构赋值
// 当解构模式有匹配结果,且匹配结果是 undefined 时,会触发默认值作为返回结果。
let [a = 2] = [undefined]; // a = 2
let [a = 3, b = a] = []; // a = 3, b = 3
let [a = 3, b = a] = [1]; // a = 1, b = 1
let [a = 3, b = a] = [1, 2]; // a = 1, b = 2
//获取this.item这个对象中的infoList的值,如果为undefined ,就将其赋值为一个空的数组
const { infoList = [] } = this.item
4. 剩余运算符
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}
const [ list, ...otherList ] = [ {data1:1}, {data2:2}, 3 ]
// list = {data1:1}
// otherList = { {data2:2}, 3 }
实例:一个数组包了三个对象,其中一个对象里面又有有个数组,即:[ {...},{...},{[...]} ]
// 1.先判断是不是数组
if (!!res && Array.isArray(res)) {
// 2. 将数组解构赋值 、{data: oneObj}:将对象解构赋值
const [{data: oneObj}, {data: twoObj}, threeArr] = res;
// 3. 赋值
this.oneObj= oneObj;
this.twoObj = twoObj;
this.threeArr = threeArr.data;
this.threeArr = threeArr.totalPage;
}