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 @ 2020-03-02 12:52  方帅  阅读(213)  评论(0编辑  收藏  举报