Break trong Functional Programming
Tương tự continue, từ khóa break không dùng được trong forEach, map, filter. Cách thay thế:
some()- Returntrueđể **break** (dừng duyệt).every()- Returnfalseđể **break**.find()/findIndex()- Tự động dừng khi tìm thấy.- Dùng
for...ofloop - Hỗ trợbreak/continuenative.
Ví dụ minh họa: Dừng khi gặp "đào" với some()
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Break in FP</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; font-family: monospace; }
button { padding: 8px 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>Break trong Functional Programming</h1>
<div class="result"></div>
<button class="btn-demo">DUYỆT VÀ DỪNG</button>
<h3>Nhấn nút để duyệt mảng, dừng khi gặp "đào"</h3>
<script>
const resEle = document.querySelector(".result");
const btn = document.querySelector(".btn-demo");
const fruits = ["táo", "xoài", "đào", "đu đủ", "dưa hấu"];
btn.addEventListener("click", () => {
resEle.textContent = "";
// some(): return true = BREAK (dừng hẳn)
fruits.some(function(fruit) {
if (fruit === "đào") {
return true; // Break - dừng vòng lặp
}
resEle.textContent += fruit + "\n";
return false; // Continue
});
resEle.textContent += "\n--- Cách tốt hơn với findIndex ---\n";
const stopIndex = fruits.findIndex(f => f === "đào");
fruits.slice(0, stopIndex).forEach(f => resEle.textContent += f + "\n");
});
</script>
</body>
</html>
So sánh Break strategies
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 1. some() - break khi tìm thấy số chẵn đầu tiên
arr.some(x => {
if (x % 2 === 0) {
console.log('First even:', x); // 2
return true; // BREAK
}
return false;
});
// 2. find() - trả về phần tử đầu tiên khớp
const firstEven = arr.find(x => x % 2 === 0); // 2
// 3. findIndex() - lấy index, rồi slice
const idx = arr.findIndex(x => x % 2 === 0); // 1
const beforeEven = arr.slice(0, idx); // [1]
// 4. for...of - break/continue native (khuyên dùng cho logic phức tạp)
for (const x of arr) {
if (x % 2 === 0) break;
console.log(x); // 1
}
Khi nào dùng cách nào?
| Tình huống | Khuyên dùng |
|---|---|
| Cần phần tử đầu tiên thỏa mãn điều kiện | find() |
| Cần index của phần tử đầu tiên thỏa mãn | findIndex() |
| Cần boolean: có tồn tại phần tử thỏa mãn? | some() |
| Cần boolean: tất cả đều thỏa mãn? | every() |
| Logic phức tạp, nhiều break/continue lồng nhau | for...of loop |
| Biến đổi mảng rồi dừng sớm | Khó với FP thuần túy, cân nhắc for...of |
Lưu ý về forEach
// KHÔNG THỂ break/continue trong forEach
[1,2,3].forEach(x => {
if (x === 2) return; // Chỉ bỏ qua iteration này (continue)
// break; // SyntaxError
// return false; // Vẫn là continue
});
// Workaround xấu (tránh dùng):
try {
[1,2,3].forEach(x => {
if (x === 2) throw 'break';
});
} catch (e) {
if (e !== 'break') throw e;
}