ES6 解构详解

一、数组解构

1. 基本用法

可以按照数组元素的顺序将数组中的值提取到变量中。

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

2. 忽略某些元素

如果不想提取数组中的某些元素,可以使用逗号占位。

const [x, , z] = [1, 2, 3];
console.log(x); // 1
console.log(z); // 3

3. 剩余元素

使用扩展运算符...可以将剩余的元素收集到一个新数组中。

const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]

4. 交换变量值

利用数组解构可以很方便地交换两个变量的值。

let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x); // 2
console.log(y); // 1

二、对象解构

1. 基本用法

根据对象的属性名来提取值并赋给变量,变量名需与属性名相同。

const obj = { name: "John", age: 30 };
const { name, age } = obj;
console.log(name); // 'John'
console.log(age); // 30

2. 自定义变量名

可以使用:为提取的变量指定不同的名称。

const { name: userName, age: userAge } = obj;
console.log(userName); // 'John'
console.log(userAge); // 30

3. 嵌套对象解构

对于嵌套的对象,也可以进行解构。

const nestedObj = {
  person: {
    name: "John",
    address: {
      city: "New York",
    },
  },
};
const {
  person: {
    name,
    address: { city },
  },
} = nestedObj;
console.log(name); // 'John'
console.log(city); // 'New York'

4. 默认值

当对象中不存在某个属性时,可以为解构的变量设置默认值。

const { gender = "Male" } = obj;
console.log(gender); // 'Male'

三、函数参数解构

1. 数组参数解构

在函数参数中使用数组解构,可以方便地获取函数传入的数组中的元素。

function sum([a, b]) {
  return a + b;
}
console.log(sum([1, 2])); // 3

2. 对象参数解构

在函数参数中使用对象解构,可以方便地获取函数传入的对象中的属性值。

function greet({ name, age }) {
  console.log(`Hello, I'm ${name} and I'm ${age} years old.`);
}
greet({ name: "John", age: 30 });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqcoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值