Vòng lặp: for, while, for...of, for...in
for cổ điển
for (let i = 0; i < 5; i++) {
console.log(i);
}while và do...while
let attempts = 0;
while (attempts < 3) {
attempts++;
}
do {
// chạy ít nhất 1 lần
} while (false);for...of — duyệt giá trị của iterable
Dùng cho array, string, Map, Set, generator…
const fruits = ["táo", "cam", "xoài"];
for (const fruit of fruits) console.log(fruit);
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}
for (const ch of "Việt") console.log(ch); // V i ệ t — đúng theo ký tự Unicodefor...in — duyệt khóa của object
const user = { name: "An", age: 20 };
for (const key in user) console.log(key, user[key]);WARNING
Không dùng for...in cho array: nó duyệt khóa dạng chuỗi ("0", "1"…) và cả thuộc tính kế thừa. Với object, Object.entries() + for...of thường rõ ràng hơn:
for (const [key, value] of Object.entries(user)) { /* ... */ }break, continue và label
for (const n of [1, 2, 3, 4, 5]) {
if (n % 2 === 0) continue; // bỏ qua số chẵn
if (n > 3) break; // dừng hẳn
console.log(n); // 1 3
}
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i * j === 2) break outer; // thoát cả hai vòng
}
}Khi nào dùng vòng lặp nào?
| Nhu cầu | Dùng |
|---|---|
| Duyệt phần tử array/iterable | for...of |
| Cần index, bước nhảy tùy ý | for cổ điển |
| Lặp tới khi điều kiện sai | while |
| Biến đổi/lọc array thành array mới | map, filter, reduce (chương 5) |
| Duyệt cặp key/value của object | Object.entries() + for...of |
Comments