第五章 解构

124 阅读2分钟

对象解构

解构可以将对象或数组中的某个属性提取到变量中

 const obj = {
     name: "a",
     age: 2,
     sex: "c"
 };
 ​
 const {name, age, sex} = obj;
 ​
 console.log(name, age, sex);        // "a" 2 "c"

在解构中使用默认值

若解构的对象中没有同名属性,将得到undefined

 const obj = {
     name: "a"
 };
 ​
 const { age } = obj;
 ​
 console.log(age);       // undefined

如果在解构的过程中,没有发现同名属性,将会使用默认值,否则将使用对应属性的值

 const obj = {
     name: "a"
 };
 ​
 const { age = 2 } = obj;
 ​
 console.log(age);       // 2

非同名属性解构

 const obj = {
     sex: "a"
 };
 ​
 const { sex: gender = "b" } = obj;
 ​
 console.log(gender);        // "a"

嵌套解构

 const obj = {
     name: "a",
     address: {
         province: "b"
     }
 };
 ​
 const {name, address: {province}} = obj;
 ​
 console.log(name, province);        // "a" "b"
 console.log(address);       // address is not defined
 // address是被解构的对象,它不是一个变量

收集剩余项

 const obj = {
     name: "a",
     age: "b",
     sex: "c"
 };
 ​
 const {name, ...rest} = obj;
 ​
 console.log(name, rest);        // "a" {age: "b", sex: "c"}

数组解构

数组本质上就是一个对象,因此可以使用对象解构的方式解构数组

由于数组的属性名是数字,数字不能作为有效的标识符,因此需要使用非同名属性解构

 var arr = [1, 2, 3];
 ​
 const {0: a, 2: c} = arr;
 ​
 console.log(a, c);      // 1 3

ES6还提供了更方便的数组解构方式

 var arr = [1, 2, 3];
 ​
 const [a, b, c] = arr;
 ​
 console.log(a, b, c);       // 1 2 3

若想跳过某些元素,可以在对应位置留空

var arr = [1, 2, 3];

const [a, , c] = arr;

console.log(a, c);		// 1 3

同样的,解构数组中不存在的元素得到的也是undefined

嵌套解构

const arr = [1, 2, [3, 4]];

const [a, b, [c, d]] = arr;

console.log(a, b, c, d);		// 1 2 3 4

收集剩余项

const arr = [1, 2, 3];

const [n1, ...rest] = arr;

console.log(n1, rest);		// 1 [2, 3]

混合解构

const arr = [1, 2, {
    name: "a",
    sex: "b"
}];

const [, , {sex}] = arr;

console.log(sex);
const obj = {
    loves: [1, 2, 3]
};

const {loves: [, , c]} = obj;

console.log(c);		// 3

参数解构

function test({name, age, sex, address: {province}}){
    console.log(name);
    console.log(age);
    console.log(sex);
    console.log(province);
}

test({
    name: "a",
    age: 2,
    sex: "c",
    address: {
        province: "d"
    }
});

参数解构与参数默认值搭配

对null或undefined进行解构将报错,因此可以给要解构的参数赋予一个默认值,用于处理用户不传递参数情况

function test({name, age} = {}){		// 左侧的{}是解构符号,右侧的{}是一个默认值对象
    console.log(name, age);		// undefined undefined
}

test();