当前位置: 首页 > article >正文

ES6 变量解构赋值总结

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); // 1

const { 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.kler.cn/a/534485.html

相关文章:

  • ES6 变量解构赋值总结
  • 虚幻UE5手机安卓Android Studio开发设置2025
  • Hackmyvm Blackhat
  • git-secret 使用教程
  • 鸿蒙Harmony-双向数据绑定MVVM以及$$语法糖介绍
  • python算法和数据结构刷题[3]:哈希表、滑动窗口、双指针、回溯算法、贪心算法
  • PostgreSQL 数据库模式基础操作
  • 蓝桥杯三国游戏(贪心)
  • 面对全球化的泼天流量,出海企业如何观测多地域网络质量?
  • ASP.NET Core中间件的概念及基本使用
  • SpringCloud速通教程
  • Vue3状态管理: Pinia使用技巧与最佳实践
  • Ubuntn24.04安装
  • windows-蓝牙驱动开发-蓝牙软件无线电开关函数原型
  • vue2-mixin的定义与和使用
  • MySQL 进阶专题:自连接、子查询与合并查询的深入探讨
  • ImGui 学习笔记(二)—— 多视口
  • Rust 中的 Packages 与 Crates:模块化构建的基础
  • 【Uniapp-Vue3】Unicloud根据表结构将数据添加到数据库
  • 5. k8s二进制集群之ETCD集群部署
  • 深入学习基础结合博客
  • 【Golang学习之旅】Go 语言基础语法概览
  • All in one 的 AI tool Chain “Halomate”
  • RAG的原理及代码实战(1)基本原理
  • TaskBuilder低代码开发项目实战—1、实战项目简介
  • linux环境自动化golang项目启动脚本解析