ES6 解构赋值

解构赋值

解构赋值可以方便快速的从数组或者对象中提取赋值给定义的变量。

获取数组中的值

从数组中获取值并赋值到变量中,变量的顺序与数组中对象顺序对应。

复制代码
 1 var foo = [1,2,3,4,5]
 2 
 3 var [one,twe,three] = foo
 4 console.log(one)//1
 5 console.log(twe)//2
 6 console.log(three)//3
 7 
 8 如果想要会略某些值,则可以
 9 
10 var [first,,last] = foo
11 console.log(first)//1
12 console.log(last)//5
13 
14 也可以先声明变量
15 
16 var a,b
17 
18 [a,b] = [1,2]
19 
20 console.log(a)//1
21 console.log(b)//2
22 
23 如果没有从数组中获取到值,可以为变量设置一个默认值
24 
25 var a,b
26 
27 [a=5,b=7]=[1]
28 
29 console.log(a)//1
30 console.log(b)//7
31 
32 方便的交互两个变量的值
33 
34 var a=1
35 var b = 3
36 
37 [a,b]=[b,a]
38 
39 console.log(a)//3
40 console.log(b)//1
复制代码

获取对象中的值

复制代码
 1 const student={
 2 name:'xxx',
 3 age:'19',
 4 city:'bj'
 5 }
 6 
 7 const {name, age,city}=student
 8 
 9 console.log(name)//xxx
10 console.log(age)//19
11 console.log(city)//bj
复制代码

 

posted @   方帅  阅读(220)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示