JavaScript解构-将数组或对象内容快速赋值给多个变量

介绍

  在以往如果我们想对数组中的某个值做特殊标注则需要不断声明容器来承载数据,而一但需求多了那么代码会显得非常臃肿,这时候一个代名词-解构- 凭空出世

目录

数组解构

差别对比

下面我将展示使用解构与不使用的两种区别

使用解构

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)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值