刘流的博客

ES6. 7.解构赋值

Word count: 628Reading time: 3 min
2020/08/30 Share

一. 数组的解构

ES5 从一个复杂的数据结构中提取数据

1
2
3
4
5
6
7
let arr = ['hello','world']

let firstName = arr[0]

let surName = arr[1]

console.log(firstName,surName);//hello world

ES6 中的解构赋值

1
2
3
4
5
let arr = ['hello','world']

let [firstName,surName] = arr

console.log(firstName,surName);//hello world

不是按照顺序提取值的话,中间可以用逗号隔开

1
2
3
4
5
let arr = ['a','b','c','d']

let [firstName, , surName] = arr

console.log(firstName,surName);//a c

左侧必须是中括号 []是这样规定的,右侧只要是可遍历的变量即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let arr = 'abcd'

let [firstName,,surName] = arr

console.log(firstName,surName);//a c



let [firstName, , surName] = new Set([1,2,3,4])

console.log(firstName,surName);//1 3



let user = {name:'s',surName:'t'}

[user.name,user.surName] = [1,2]

console.log(user);//{name: 1, surName: 2}

ES5 的做法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
let arr = ['hello','world']

for (let i = 0,item; i < arr.length; i++) {

item = arr[i]

}



let user = {name:'s',surname:'t'}

for (let [k,v] of Object.entries(user)) {

console.log(k,v);

}

// name s

// surname t



let arr = [1,2,3,4,5,6,7,8,9]

let [firstName,curName,...last] = arr

console.log(firstName,curName,last);

// 1 2 [

// 3, 4, 5, 6,

// 7, 8, 9

// ]



let arr = []

let [firstName,curName,...last] = arr

console.log(firstName,curName,last);// undefined undefined []



let arr = []

let [firstName = 'hello',curName,...last] = arr

console.log(firstName,curName,last);// hello undefined []

二. 对象的解构

从对象中解构可以将属性改名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let options = {

title:'menu',

width:100,

height:200

}



let {title:title2,width,height} = options

console.log(title2,width,height);//menu 100 200

可以给属性一个默认值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let options = {

title:'menu',

// width:100,

height:200

}



let {title:title2,width =130 ,height} = options

console.log(title2,width,height);//menu 130 200

也可以使用剩余参数来储存其他的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let options = {

title:'menu',

width:100,

height:200

}



let {title,...last} = options

console.log(title,last);//menu { width: 100, height: 200 }

当对象里面也有对象的时候,我们仍然可以使用解构的方式获取属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
let options = {

size:{

​ width:100,

​ height:200

},

items:['cake','Dount'],

extra:true

}



// 获取属性值

let { size:{width}} = options

console.log(width);//100



// 将属性值改名

let { size:{width:width2,height}} = options

console.log(width2,height);//100 200



// 获取对象中的数组

let { size:{width:width2,height }, items:[item1]} = options

console.log(width2,height,item1);//100 200 cake
CATALOG
  1. 1. 一. 数组的解构