Khái niệm
Destructuring Assignment là cú pháp đặc biệt cho phép "bóc tách" giá trị từ mảng hoặc thuộc tính từ đối tượng và gán vào các biến riêng biệt. Hỗ trợ cả mảng và đối tượng, có thể kết hợp giá trị mặc định và đổi tên biến.
Ví dụ: Phân rã mảng và đối tượng
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Destructuring Assignment</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.sample, .result { font-size: 16px; font-weight: 500; margin: 10px 0; padding: 10px; border-radius: 4px; }
.sample { color: #d32f2f; background: #ffebee; }
.result { color: #6a1b9a; background: #f3e5f5; }
button { padding: 8px 16px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h1>Phép gán phân rã trong JavaScript</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result"></div>
<button id="btn">THỰC HIỆN PHÂN RÃ</button>
<h3>Nhấn nút để phân rã mảng và đối tượng</h3>
<script>
const sampleEle = document.getElementById('sample');
const resultEle = document.getElementById('result');
const btn = document.getElementById('btn');
const arr = [2, 3, 4, 5];
const obj = { firstName: 'Rohan', lastName: 'Sharma' };
sampleEle.innerHTML = `Mảng: ${arr} <br>`;
sampleEle.innerHTML += `Đối tượng: {firstName: 'Rohan', lastName: 'Sharma'}`;
// Phân rã mảng - lấy 2 phần tử đầu
let a, b;
[a, b] = arr;
// Phân rã đối tượng
let { firstName, lastName } = obj;
btn.addEventListener('click', () => {
resultEle.innerHTML = `a=${a} b=${b} <br>`;
resultEle.innerHTML += `firstName=${firstName} lastName=${lastName}`;
});
</script>
</body>
</html>
Kết quả
Hiển thị: a=2 b=3 và firstName=Rohan lastName=Sharma
Các kỹ thuật nâng cao
1. Bỏ qua phần tử (mảng)
const [first, , third] = [1, 2, 3];
console.log(first, third); // 1 3
2. Rest operator (phần tử còn lại)
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
3. Giá trị mặc định
const [x = 1, y = 2] = [];
console.log(x, y); // 1 2
const { name = 'Anonymous', age = 0 } = {};
console.log(name, age); // Anonymous 0
4. Đổi tên biến (đối tượng)
const { firstName: fn, lastName: ln } = obj;
console.log(fn, ln); // Rohan Sharma
5. Phân rã tham số hàm
function greet({ name, age = 18 }) {
console.log(`Xin chào ${name}, ${age} tuổi`);
}
greet({ name: 'Minh' }); // Xin chào Minh, 18 tuổi