ECMAScript的解构赋值怎么用
ECMAScript 6(ES6)引入了解构赋值,这是一种允许我们从数组或对象中提取数据并赋值给变量的简洁方法。解构赋值可以使代码更简洁、易读。
- 数组解构赋值:
 
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a); // 输出 1
console.log(b); // 输出 2
console.log(c); // 输出 3
- 对象解构赋值:
 
const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};
const { name, age, city } = obj;
console.log(name); // 输出 'John'
console.log(age); // 输出 30
console.log(city); // 输出 'New York'
- 默认值:
 
const arr = [1, 2];
const [a, b, c = 3] = arr;
console.log(a); // 输出 1
console.log(b); // 输出 2
console.log(c); // 输出 3
- 交换变量值:
 
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 输出 2
console.log(b); // 输出 1
- 函数参数解构:
 
function greet({ name, age }) {
  console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
const person = {
  name: 'John',
  age: 30
};
greet(person); // 输出 'Hello, my name is John and I am 30 years old.'
解构赋值在实际开发中非常实用,可以让代码更简洁、易读。