数组的解构和对象的解构
一、数组的解构
数组:
const arr = [100, 200, 300]
1.1 解构获取所有值
常规数组值的获取是通过索引:
const iNum1 = arr[0]
const iNum2 = arr[1]
const iNum3 = arr[2]
console.log(iNum1, iNum2, iNum3)
// 100 200 300
通过数组解构进行:
const [iNum1, iNum2, iNum3] = arr;
console.log(iNum1, iNum2, iNum3)
// 100 200 300
1.2 解构数组获取部分值
获取第一个值:
const [iNum1] = arr
console.log(iNum1)
// 100
获取中间值:
const [, iNum2] = arr
console.log(iNum2)
// 200
const [, ,iNum3] = arr
console.log(iNum3)
// 300
获取后方数据:
const [iNum1, ...rest] = arr
console.log(rest)
// [200 300]
1.3解构参数大于数组长度
const [iNum1, iNum2, iNum3, iNum4] = arr
console.log(iNum1, iNum2, iNum3, iNum4)
// 100 200 300 undefined
设置默认值:
const [iNum1, iNum2, iNum3, iNum4=123] = arr
console.log(iNum1, iNum2, iNum3, iNum4)
// 100 200 300 123
1.4例子
获取根路径:
const path = '/root/demo'
方式一:
const arr = path.split('/')
console.log(arr[1]);
// root
方式二:
const [,rootdir] = path.split('/')
console.log(rootdir)
// root
二、对象解构
对象:
const obj = { name: "radish", age: 18, height: 180 }
常规方式:
const name = obj.name
const age = obj.age
const height = obj.height
console.log(name, age, height)
// radish 18 180
2.1解构获取所有值
const {name, age, height} = obj
console.log(name, age, height)
// radish 18 180
和数组解构相比将[]
更换为{}
2.2 解构获取特定值
const {age} = obj
console.log(age)
// 18
const {name} = obj
console.log(name)
// radish
2.3解构获取后方数据
const {name, ...rest} = obj
console.log(name)
console.log(rest)
// radish
// { age: 18, height: 180 }
2.4设置默认值
const {gender='man'} = obj
console.log(gender)
// man