Cấu trúc 3 phần
for (initialization; condition; iteration) {
// body
}
- Initialization: chạy 1 lần đầu (khởi tạo biến đếm).
- Condition: kiểm tra trước mỗi lần lặp. True → chạy body.
- Iteration: chạy sau mỗi lần lặp (thường i++).
Ví dụ
<script>
document.write("Bat dau vong lap<br>");
for (var count = 0; count < 10; count++) {
document.write("Current Count: " + count + "<br>");
}
document.write("Vong lap dung!<br>");
</script>
Biến thể
- Pom nhiều biến:
for (let i=0, j=10; i
- Bỏ qua phần:
for (;;) = vô tận (cần break bên trong).
- Let/const (ES6):
for (let i=0; ...) – block-scoped, fix closure issue.
For...of (ES6) – Duyệt giá trị
for (const item of array) { ... }
for (const char of "hello") { ... }
for (const [key, value] of map) { ... }
For...in – Duyệt key (property name)
for (const key in object) { ... }
// Duyệt prototype chain – cần hasOwnProperty check
Khuyến nghị
- Dùng
for...of cho array/iterable (đơn giản, đúng ngữ nghĩa).
- Dùng
for truyền thống khi cần index, step tùy chỉnh, break/continue phức tạp.
- Tránh
for...in cho array (duyệt key string, bao gồm prototype).