ES6 变量解构赋值总结

devtools/2025/2/8 0:27:35/

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/devtools/156971.html

相关文章

音视频多媒体编解码器基础-codec

如果要从事编解码多媒体的工作,需要准备哪些更为基础的内容,这里帮你总结完。 因为数据类型不同所以编解码算法不同,分为图像、视频和音频三大类;因为流程不同,可以分为编码和解码两部分;因为编码器实现不…

25/2/6 <机器人基础> 运动学中各连杆的变换矩阵求法

变换矩阵 机器人通常包含多个关节和连杆,每个关节和连杆都有自己的局部坐标系。变换矩阵能够将一个点或向量从一个坐标系转换到另一个坐标系,从而实现对机器人各个部件位置和姿态的统一描述 变换矩阵能够将复杂的运动分解为旋转和平移的组合。通过矩阵乘…

2021.3.1的android studio版本就很好用

使用最新版的studio有个问题就是gradle版本也比较高,这样就容易出现之前项目不兼容问题,配置gradle可能会出现很多问题比较烦,所以干脆就用老版本的studio

langchain教程-2.prompt

前言 该系列教程的代码: https://github.com/shar-pen/Langchain-MiniTutorial 我主要参考 langchain 官方教程, 有选择性的记录了一下学习内容 这是教程清单 1.初试langchain2.prompt3.OutputParser/输出解析4.model/vllm模型部署和langchain调用5.DocumentLoader/多种文档…

【漫话机器学习系列】079.超参数调优(Hyperparameter Tuning)

超参数调优(Hyperparameter Tuning)是机器学习中优化模型性能的重要步骤之一。超参数是模型在训练之前设定的参数,而不是通过训练数据学习到的参数。正确地选择超参数可以显著提高模型的预测能力,反之,错误的超参数选择…

使用 CSS 实现透明效果

在 CSS 中,实现透明效果有几种方法,具体使用哪种方法取决于具体需求。以下是一些常见的方法: 使用 opacity 属性: opacity 属性可以设置整个元素的透明度,包括其所有的子元素。 .transparent { opacity: 0.5; /* 0 表…

基础相对薄弱怎么考研

复习总体规划 明确目标 选择专业和院校:根据你的兴趣、职业规划和自身实力,选择适合自己的专业和院校。可以参考往年的分数线、报录比、复试难度等。了解考试科目:不同专业考试科目不同,一般包括: 公共课&#xff1a…

Pikachu漏洞靶场搭建|phpstudy下载安装(保姆级教程)

pikachu是一个漏洞练习平台。其中包含了常见的web安全漏洞 ​ 但是它需要一个PHP的集成环境 而phpStudy是一个PHP调试环境的程序集成包 该程序包集成最新的ApachePHPMySQLphpMyAdminZendOptimizer,一次性安装,无须配置即可使用,是非常方便、好用的PHP调试环境.该…