解构是ES2015新增的从数组或对象中获取指定元素的一种快捷方式,这是一种新的语法。
数组解构的基本使用:
const arr = ['Judy', 'Alex', 'Carl']
// ES2015之前获取指定元素需要通过索引获取然后放到一个变量当中
const user1 = arr[0]
const user2 = arr[1]
const user3 = arr[2]
console.log(user1, user2, user3) // Judy Alex Carl
// ES2015之后可以使用解构快速提取数组的成员,根据左侧变量位置获取对应的成员
const [user01, user02, user03] = arr
console.log(user01, user02, user03) // Judy Alex Carl
// 省略变量获取某个或某几个元素
const [,,user13] = arr
console.log(user13) // Carl
// ...提取从当前位置往后的所有成员,结果放在一个数组中,这种用法只能在最后一个成员上使用
const [user11, ...users] = arr
console.log(user11, users) // Judy [ 'Alex', 'Carl' ]
// 解构成员个数小于数组元素个数则按照从前到后的顺序依次提取,多出来的成员不提取
const brr = [1,2,3,4,5]
const [a,b] = brr
console.log(a,b) // 1 2
// 解构成员的个数大于数组元素的个数,那超出元素个数的变量提取的值为undefined,跟访问数组中不存在的下标是一样的
const crr = ['apple', 'pear']
const [apple, pear, orange] = crr
console.log(apple, pear, orange) // apple pear undefined
// 给提取不到的成员设置默认值,例如此处的orange1
const [apple1, pear1, orange1 = 'orange'] = crr
console.log(apple1, pear1, orange1) // apple pear orange
数组解构的使用场景:
// 拆分字符串获取拆分后的制定位置
const path = '/a/b/c'
// 传统方法
const tmp = path.split('/')
const rootPath = tmp[1]
const secondPath = tmp[2]
console.log(rootPath) // a
// 解构的方法:更简单,可以省略中间变量tmp
const [, rootPath1, secondPath2] = path.split('/')
console.log(rootPath1) // a