Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phân rã mảng (Array Destructuring) trong JavaScript

Destructuring assignment (phân rã gán) là cú pháp ES6 cho phép "đóng gói" giá trị từ mảng hoặc thuộc tính từ object vào các biến riêng lẻ một cách ngắn gọn, dễ đọc.

Cú pháp cơ bản với mảng

const [a, b, c] = array;

Ví dụ hoàn chỉnh

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Array Destructuring</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
        .sample { font-size: 1.2rem; font-weight: 500; margin: 1rem 0; }
        .result { font-size: 1.1rem; font-weight: 500; color: green; white-space: pre-line; }
        button { padding: 0.5rem 1rem; background: #6f42c1; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
        button:hover { background: #5a32a3; }
    </style>
</head>
<body>
    <h1>Phân rã mảng (Destructuring) trong JavaScript</h1>
    <div class="sample" id="sampleEl"></div>
    <div class="result" id="resultEl"></div>
    <button id="btn">PHÂN RÃ MẢNG</button>
    <p>Nhấn nút để phân rã mảng ["F", "G", 22, 44]</p>

    <script>
        const sampleEl = document.getElementById('sampleEl');
        const resultEl = document.getElementById('resultEl');
        const arr = ["F", "G", 22, 44];
        
        sampleEl.textContent = `Mảng gốc: [${arr.join(', ')}]`;
        
        document.getElementById('btn').addEventListener('click', () => {
            // Phân rã mảng vào 4 biến
            const [a, b, c, d] = arr;
            resultEl.textContent = `Sau phân rã:\na = ${a}\nb = ${b}\nc = ${c}\nd = ${d}`;
        });
    </script>
</body>
</html>

Kết quả

Mảng gốc: ["F", "G", 22, 44]

Sau phân rã:

a = F
b = G
c = 22
d = 44

Kỹ thuật nâng cao

1. Bỏ qua phần tử

const [first, , third] = [1, 2, 3]; // first=1, third=3

2. Giá trị mặc định

const [x = 10, y = 20] = [5]; // x=5, y=20 (mặc định)

3. Rest operator (phần còn lại)

const [head, ...tail] = [1, 2, 3, 4];
// head = 1, tail = [2, 3, 4]

4. Hoán đổi biến (swap)

let a = 1, b = 2;
[a, b] = [b, a]; // a=2, b=1

5. Destructuring trong tham số hàm

function greet([first, last]) {
    console.log(`Xin chào ${first} ${last}`);
}
greet(["Nguyễn", "Văn A"]);