JavaScript 解构赋值
解构赋值(Destructuring Assignment)是 JavaScript ES6 引入的一种新语法,可以从数组或对象中提取值,赋值给变量。它使代码更加简洁易读,尤其在处理复杂数据结构时。
数组解构
数组解构允许我们按照数组的顺序提取元素,并赋值给变量。
const fruits = ["apple", "banana", "cherry"];
// 基本用法
const [first, second, third] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
console.log(third); // "cherry"
对象解构
对象解构根据属性名提取值,并赋值给相应的变量。
const person = {
name: "Alice",
age: 25,
location: "Wonderland"
};
// 基本用法
const { name, age, location } = person;
console.log(name); // "Alice"
console.log(age); // 25
console.log(location); // "Wonderland"
默认值
在解构过程中,可以为变量提供默认值,当对应的数组元素或对象属性不存在时,使用默认值。
const fruits = ["apple"];
// 数组解构默认值
const [first, second = "banana"] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
const person = {
name: "Alice"
};
// 对象解构默认值
const { name, age = 30 } = person;
console.log(name); // "Alice"
console.log(age); // 30
剩余参数
剩余参数(Rest Parameter)用于获取数组或对象中剩余的部分。
const fruits = ["apple", "banana", "cherry", "date"];
// 数组解构的剩余参数
const [first, second, ...rest] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
console.log(rest); // ["cherry", "date"]
const person = {
name: "Alice",
age: 25,
location: "Wonderland",
profession: "Explorer"
};
// 对象解构的剩余参数
const { name, age, ...others } = person;
console.log(name); // "Alice"
console.log(age); // 25
console.log(others); // { location: "Wonderland", profession: "Explorer" }