介绍
在以往如果我们想对数组中的某个值做特殊标注则需要不断声明容器来承载数据,而一但需求多了那么代码会显得非常臃肿,这时候一个代名词-解构-
凭空出世
目录
文章目录
数组解构
差别对比
下面我将展示使用解构与不使用的两种区别
使用解构
const [max, min, avg] = [100, 60, 80]
console.log(max) // 100
console.log(avg) // 80
不使用解构
const arr = [100, 60, 80]
const max = arr[0]
const min = arr[1]
const avg = arr[2]
console.log(max) // 100
console.log(avg) // 80
从上面两个代码块内容对比就很容易看出,如果不使用解构那么你的代码会显得特别臃肿同时也会显得特别不专业
交换两个变量的值
// 交换2个变量的值
let a = 1
let b = 2;
[b, a] = [a, b]
console.log(a, b)
数组解构细节
在讲之前要先普及文章中使用的关键字所代表的意思
单元值:指数组中具体的每一个值
1. 变量多, 单元值少
const [a, b, c, d] = [1, 2, 3]
console.log(a) // 1
console.log(b) // 2
console.log(c) // 3
console.log(d) // undefined
2. 变量少, 单元值多
const [a, b] = [1, 2, 3]
console.log(a) // 1
console.log(b) // 2
3. 剩余参数 变量少, 单元值多
const [a, b, ...c] = [1, 2, 3, 4]
console.log(a) // 1
console.log(b) // 2
console.log(c) // [3, 4] 真数组
4. 防止 undefined 传递
const [a = 0, b = 0] = [1, 2]
// const [a = 0, b = 0] = []
console.log(a) // 1
console.log(b) // 2
5. 按需导入赋值
const [a, b, , d] = [1, 2, 3, 4]
console.log(a) // 1
console.log(b) // 2
console.log(d) // 4
多维数组解构
const arr = [1, 2, [3, 4]]
const [a, b, c] = arr
console.log(a) // 1
console.log(b) // 2
console.log(c) // [3,4]
const [a, b, [c, d]] = [1, 2, [3, 4]]
console.log(a) // 1
console.log(b) // 2
console.log(c) // 3
console.log(d) // 4
对象解构
对象解构在日常开发中使用较多,平时后端请求过来对象数据都会使用解构
- 要求属性名(对象内的属性)和变量名(为变量声明所用)必须一致才可以
语法
//解构语法
const { uname, age } = {age: 18, uname: 'pink老师' }
// 等价于 const uname = obj.uname
console.log(uname)
console.log(age)
1. 对象解构的变量名 可以重新改名
在开发中如果出现了变量重复声明报错的情况我们可以使用这种方式从解构上来做更改
// 旧变量名: 新变量名
const { uname: username, age } = { uname: 'pink老师', age: 18 }
console.log(username)
console.log(age)
2. 解构数组对象
const pig = [
{
uname: '佩奇',
age: 6
}
]
const [{ uname, age }] = pig
console.log(uname)
console.log(age)
多级对象解构
最外层对象
const pig = {
name: '佩奇',
family: {
mother: '猪妈妈',
father: '猪爸爸',
sister: '乔治'
},
age: 6
}
// 多级对象解构
const { name, family: { mother, father, sister } } = pig
console.log(name)
console.log(mother)
console.log(father)
console.log(sister)
最外层数组
const person = [
{
name: '佩奇',
family: {
mother: '猪妈妈',
father: '猪爸爸',
sister: '乔治'
},
age: 6
}
]
const [{ name, family: { mother, father, sister } }] = person
console.log(name)
console.log(mother)
console.log(father)
console.log(sister)