4.ES6 变量的解构赋值

 

变量的解构赋值

ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构赋值。

注意:频繁使用对象方法、数组元素,就可以使用解构赋值形式

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
// 1.数组
const fruits = ["apple", "banana", "grapes", "orange"];
let [e1, e2, e3, e4, e5] = fruits;
console.log(e1);
console.log(e2);
console.log(e3);
console.log(e4);
console.log(e5);
/**
* apple
* banana
* grapes
* orange
* undefined
*/

// 2.对象
const student = {
id: 1,
name: "xiaoming",
age: 10,
study: function() {
console.log("studying");
}
}
let {id, name, age, study, address} = student;
console.log(id);
console.log(name);
console.log(age);
console.log(study);
console.log(address);
/**
* 1
* xiaoming
* 10
* ƒ () {
* console.log("studying");
* }
* undefined
*/

let {study} = student;
study();
/**
* studying
*/