树欲静而风不止
叙述前端的戎码生涯

学会这 12 个解构用法,代码量能省一半

解构赋值是 ES6 带来的重要特性之一,掌握好它不仅能让代码更简洁,还能大大提高开发效率。分享 12 个实用的解构用法,让你的代码更优雅。

1. 数组基础解构

最基本的数组解构让我们能够轻松地提取数组元素:

// 基础解构  
const [first, second] = [1, 2, 3];  
console.log(first);  // 1  
console.log(second); // 2  
​  
// 跳过元素  
const [, , third] = [1, 2, 3];  
console.log(third);  // 3

2. 对象解构重命名

当我们需要避免命名冲突时,可以给解构的属性起新名字:

const person = {  
  name: '张三',  
  age: 25  
};  
​  
const { name: userName, age: userAge } = person;  
console.log(userName); // '张三'  
console.log(userAge);  // 25

3. 设置默认值

解构时可以设置默认值,防止取到 undefined:

// 数组默认值  
const [x = 1, y = 2] = [undefined, null];  
console.log(x); // 1  
console.log(y); // null  
​  
// 对象默认值  
const { title = '默认标题', count = 0 } = {};  
console.log(title); // '默认标题'  
console.log(count); // 0

4. 嵌套解构

对于复杂的嵌套数据结构,我们可以使用嵌套解构:

const user = {  
  id: 1,  
  info: {  
    name: '李四',  
    address: {  
      city: '北京'  
    }  
  }  
};  
​  
const { info: { name, address: { city } } } = user;  
console.log(name); // '李四'  
console.log(city); // '北京'

5. 结合扩展运算符

扩展运算符配合解构使用,能够轻松处理剩余元素:

// 数组结合扩展运算符  
const [head, ...tail] = [1, 2, 3, 4];  
console.log(head); // 1  
console.log(tail); // [2, 3, 4]  
​  
// 对象结合扩展运算符  
const { id, ...rest } = { id:1, name:'王五', age: 30 };  
console.log(id); // 1  
console.log(rest); // {name:'王五', age: 30 }

6. 函数参数解构

在函数参数中使用解构可以让代码更清晰:

// 对象参数解构  
function printUser({name,age=18 }){  
    console.log(`${name} 今年 ${age} 岁`);  
}  
printUser({name:'赵六'}); // "赵六今年18 岁"  
​  
// 数组参数解构  
function sum([a, b] = [0, 0]) {  
    return a + b;  
}  
console.log(sum([1, 2])); // 3

7. 动态属性解构

可以使用计算属性名进行解构:

const key = 'name';  
const { [key]: value } = { name:'小明' };  
console.log(value); // '小明'

8. 解构用于交换变量

使用解构可以优雅地交换变量值:

let a = 1, b = 2;  
[a, b] = [b, a];  
console.log(a); // 2  
console.log(b); // 1

9. 链式解构赋值

可以在一行中进行多个解构赋值:

const obj = { a:1, b:2 };  
const arr = [3, 4];  
const { a, b } = obj, [c, d] = arr;

10. 解构配合正则匹配

在处理正则表达式结果时,解构特别有用:

const [, year, month, day] = /(\d{4})-(\d{2})-(\d{2})/.exec('2024-02-23');  
console.log(year, month, day); // '2024' '02' '23'

11. 解构导入模块

在导入模块时,解构可以只引入需要的部分:

// 只导入需要的方法  
import { useState, useEffect } from 'react';  
​  
// 重命名导入  
import { useState as useStateHook } from 'react';

12. 条件解构

结合空值合并运算符,可以实现条件解构:

const data = null;  
const { value = 'default' } = data ?? {};  
console.log(value); // 'default'
赞(0)
未经允许不得转载:OveUI » 学会这 12 个解构用法,代码量能省一半
分享到