ES6 变量解构赋值总结

news/2025/2/7 1:25:25/

1. 数组的解构赋值

1.1 基本用法

// 基本数组解构
const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3// 跳过某些值
const [x, , y] = [1, 2, 3];
console.log(x); // 1
console.log(y); // 3// 解构剩余元素
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest);  // [2, 3, 4, 5]

1.2 默认值

// 设置默认值
const [x = 1, y = 2] = [undefined, null];
console.log(x); // 1  (使用默认值)
console.log(y); // null (使用解构值)// 复杂默认值
const [a = 1, b = a + 1] = [2];
console.log(a); // 2
console.log(b); // 3

2. 对象的解构赋值

2.1 基本用法

// 基本对象解构
const { name, age } = { name: 'John', age: 25 };
console.log(name); // 'John'
console.log(age);  // 25// 变量重命名
const { name: userName, age: userAge } = { name: 'John', age: 25 };
console.log(userName); // 'John'
console.log(userAge);  // 25// 嵌套解构
const { name, address: { city, country } 
} = { name: 'John', address: { city: 'New York', country: 'USA' } 
};
console.log(name);    // 'John'
console.log(city);    // 'New York'
console.log(country); // 'USA'

2.2 默认值

// 对象属性默认值
const { name = 'Anonymous', age = 18 } = { name: 'John' };
console.log(name); // 'John'
console.log(age);  // 18// 重命名并设置默认值
const { name: userName = 'Anonymous', age: userAge = 18 } = {};
console.log(userName); // 'Anonymous'
console.log(userAge);  // 18

3. 函数参数的解构赋值

3.1 数组参数解构

// 数组参数解构
function sum([x, y]) {return x + y;
}
console.log(sum([1, 2])); // 3// 带默认值的数组参数解构
function move([x = 0, y = 0] = []) {return [x, y];
}
console.log(move([1, 2])); // [1, 2]
console.log(move([1]));    // [1, 0]
console.log(move([]));     // [0, 0]
console.log(move());       // [0, 0]

3.2 对象参数解构

// 对象参数解构
function printUser({ name, age }) {console.log(\`\${name} is \${age} years old\`);
}
printUser({ name: 'John', age: 25 }); // "John is 25 years old"// 带默认值的对象参数解构
function fetchAPI({ url, method = 'GET', headers = { 'Content-Type': 'application/json' } 
} = {}) {return { url, method, headers };
}console.log(fetchAPI({ url: '/api/users' }));
// { 
//   url: '/api/users', 
//   method: 'GET', 
//   headers: { 'Content-Type': 'application/json' } 
// }

4. 实际应用场景

4.1 交换变量

// 不使用临时变量交换值
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x); // 2
console.log(y); // 1

4.2 从函数返回多个值

function getUserInfo() {return {name: 'John',age: 25,email: 'john@example.com'};
}const { name, email } = getUserInfo();
console.log(name);  // 'John'
console.log(email); // 'john@example.com'

4.3 处理 API 响应

async function fetchUserData() {const response = await fetch('https://api.example.com/user');const { id, name, profile: { age, avatar } } = await response.json();return {userId: id,userName: name,userAge: age,userAvatar: avatar};
}

4.4 模块导入

// 从模块中选择性导入
import { useState, useEffect } from 'react';// 重命名导入
import { useState as useStateHook } from 'react';

5. 注意事项和最佳实践

5.1 解构失败的处理

// 解构失败时的默认值
const [a = 1] = [];
console.log(a); // 1const { name = 'Anonymous' } = {};
console.log(name); // 'Anonymous'// 防止解构undefined
const { x = 1 } = null || {}; // 避免直接解构 null
console.log(x); // 1

5.2 解构嵌套对象

// 使用别名简化深层解构
const {user: {profile: { address: userAddress }}
} = response;// 或者分步解构提高可读性
const { user } = response;
const { profile } = user;
const { address } = profile;

5.3 解构与类型检查

// TypeScript中的解构
interface User {name: string;age: number;address?: {city: string;country: string;};
}function processUser({ name, age, address = { city: '', country: '' } }: User) {// 使用解构的值
}

http://www.ppmy.cn/news/1569950.html

相关文章

day37|完全背包基础+leetcode 518.零钱兑换II ,377.组合总和II

完全背包理论基础 完全背包与01背包的不同在于01背包的不同物品每个都只可以使用一次,但是完全背包的不同物品可以使用无数次 在01背包理论基础中,为了使得物品只被使用一次,我们采取倒序遍历来控制 回顾:>> for(int j …

STM32 DMA数据转运

DMA简介 DMA(Direct Memory Access)直接存储器存取 DMA可以提供外设和存储器或者存储器和存储器之间的高速数据传输,无须CPU干预,节省了CPU的资源 12个独立可配置的通道: DMA1(7个通道)&#xf…

RTMP 和 WebRTC

WebRTC(Web Real-Time Communication)和 RTMP(Real-Time Messaging Protocol)是两种完全不同的流媒体协议,设计目标、协议栈、交互流程和应用场景均有显著差异。以下是两者的详细对比,涵盖协议字段、交互流程及核心设计思想。 一、协议栈与设计目标对比 特性RTMPWebRTC传…

Spring Web MVC基础第一篇

目录 1.什么是Spring Web MVC? 2.创建Spring Web MVC项目 3.注解使用 3.1RequestMapping(路由映射) 3.2一般参数传递 3.3RequestParam(参数重命名) 3.4RequestBody(传递JSON数据) 3.5Pa…

JVM执行流程与架构(对应不同版本JDK)

直接上图(对应JDK8以及以后的HotSpot) 这里主要区分说明一下 方法区于 字符串常量池 的位置更迭: 方法区 JDK7 以及之前的版本将方法区存放在堆区域中的 永久代空间,堆的大小由虚拟机参数来控制。 JDK8 以及之后的版本将方法…

python-leetcode-验证二叉搜索树

98. 验证二叉搜索树 - 力扣(LeetCode) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val0, leftNone, rightNone): # self.val val # self.left left # self.right right class Soluti…

信息安全、网络安全和数据安全的区别和联系

一、区别 1.信息安全 定义 信息安全是指为数据处理系统建立和采用的技术和管理的安全保护,保护计算机硬件、软件和数据不因偶然和恶意的原因而遭到破坏、更改和泄露。它的范围比较广泛,涵盖了信息的保密性、完整性和可用性等多个方面。 侧重点 更强…

Nginx 命令行参数

文章来源:命令行参数 -- nginx中文文档|nginx中文教程 nginx 支持以下命令行参数: -?| — 打印帮助 以获取命令行参数。-h-c file— 使用替代项 configuration 而不是 default 文件。file-e file— 使用替代项 error log 来存储日志 而不是默认文件 &…