Vòng lặp for...of (được giới thiệu trong ES2015/ES6) cho phép lặp qua các đối tượng có thể lặp (iterable) như: Array, String, Map, Set, NodeList, arguments, v.v. Cú pháp ngắn gọn, dễ đọc hơn for truyền thống.
Cú pháp
for (const element of iterable) {
// code thực thi với mỗi element
}
Ví dụ: Lặp qua chuỗi (String)
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vòng lặp for...of</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; color: #333; }
.result { font-size: 1.1rem; font-weight: 500; color: green; white-space: pre-line; }
button { padding: 0.5rem 1rem; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
button:hover { background: #218838; }
</style>
</head>
<body>
<h1>Vòng lặp for...of trong JavaScript</h1>
<div class="sample" id="sampleEl"></div>
<div class="result" id="resultEl"></div>
<button id="btn">CHẠY VÓNG LẶP</button>
<p>Nhấn nút để lặp qua chuỗi "Hello" bằng for...of</p>
<script>
const sampleEl = document.getElementById('sampleEl');
const resultEl = document.getElementById('resultEl');
const str = "Hello";
sampleEl.textContent = `Chuỗi gốc: "${str}"`;
document.getElementById('btn').addEventListener('click', () => {
resultEl.textContent = ''; // Xóa kết quả cũ
for (const char of str) {
resultEl.textContent += char + '\n';
}
});
</script>
</body>
</html>
Kết quả
Ban đầu: Hiển thị chuỗi "Hello"
Sau khi nhấn nút: Mỗi ký tự trên một dòng:
H
e
l
l
o
Các trường hợp sử dụng phổ biến
| Đối tượng | Ví dụ |
|---|---|
| Mảng | for (const item of arr) |
| Map | for (const [key, value] of map) |
| Set | for (const val of set) |
| NodeList | for (const node of document.querySelectorAll('div')) |
So sánh nhanh
for...of: Lặp giá trị (values).for...in: Lặp khóa (key/index) - dùng cho object thường.forEach(): Phương thức mảng, không thểbreak/continue.