Z
ZHANK
数组与对象

解构赋值

学习数组和对象的解构语法与默认值

解构赋值

解构赋值让你用简洁的语法提取数组和对象中的值。

学完本章你将: 掌握数组解构、对象解构与默认值。


数组解构

javascript
// 基本解构
let colors = ["红", "绿", "蓝"];
let [first, second, third] = colors;
console.log(first);  // "红"

// 跳过元素
let [a, , c] = ["x", "y", "z"];
console.log(a, c);   // "x" "z"

// 默认值
let [p = 1, q = 2] = [10];
console.log(p, q);   // 10 2

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

// 剩余模式
let [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]

对象解构

javascript
let user = {
    name: "Alice",
    age: 25,
    address: {
        city: "北京",
        province: "北京",
    },
};

// 基本解构
let { name, age } = user;
console.log(name); // "Alice"

// 重命名
let { name: userName, age: userAge } = user;
console.log(userName); // "Alice"

// 默认值
let { name = "Unknown", email = "no@email" } = user;
console.log(email); // "no@email"

// 嵌套解构
let { address: { city, province } } = user;
console.log(city); // "北京"

函数参数解构

javascript
// 对象参数解构
function display({ name, age, city = "未知" }) {
    console.log(`${name}${age}岁)来自 ${city}`);
}
display({ name: "Alice", age: 25, city: "北京" });

// 带默认值的解构参数
function fetch({ url, method = "GET", timeout = 5000 } = {}) {
    console.log(`${method} ${url} timeout=${timeout}`);
}
fetch({ url: "/api/data" }); // "GET /api/data timeout=5000"

// 剩余模式
function log(first, ...others) {
    console.log(first, others);
}
log(1, 2, 3, 4, 5); // 1 [2, 3, 4, 5]

实战技巧

javascript
// 1. 从函数返回多个值
function getMinMax(arr) {
    return [Math.min(...arr), Math.max(...arr)];
}
let [min, max] = getMinMax([3, 1, 4, 1, 5]);
console.log(min, max); // 1 5

// 2. 提取 API 响应
let response = {
    data: { id: 1, title: "Hello" },
    status: 200,
};
let { data: { id, title }, status } = response;
console.log(id, title, status); // 1 "Hello" 200

// 3. 正则匹配
let [, month, day] = /^(\d{2})-(\d{2})/.exec("12-25");
console.log(month, day); // "12" "25"