循环
for, 虽然, for...的, for...in, and 如何 break and continue iteration.
你将学到
- classic for 循环 and 当到 use 它
- 虽然 and 做...虽然循环
- for...的 for iterating iterable 值 (数组, 字符串)
- for...in for iterating 对象键 (and 为什么到 是 careful)
- break and continue 到 control 循环 flow
概念讲解
The Classic for Loop
Use it when you need the index:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
while and do...while
虽然 checks the condition before each iteration. 做...虽然 checks it after, so the body always runs at least once:
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
let n = 0;
do {
console.log("运行 at 最少一次");
} while (n > 0);
for...of — for values
for...的 iterates over iterable values — arrays, strings, maps, sets. This is the modern, idiomatic way to loop through a collection:
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
for (const char of "Hello") {
console.log(char); // H, e, l, l, o
}
for...in — for keys (be careful!)
for...in iterates over enumerable property keys of an object. It is not meant for arrays — it can return indices as strings and include inherited properties:
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]); // "" 1, "b" 2, "c" 3
}
// Do NOT use for...in with arrays!
const arr = [10, 20, 30];
for (const i in arr) {
console.log(i); // "0", "1", "2" — strings, not numbers
}
Rule: for...of for arrays and strings (values), for...in for objects (keys).
break and continue
breakexits the loop entirely.continueskips the rest of the current iteration and moves to the next.
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // skip 3
if (i === 7) break; // stop at 7
console.log(i); // 0, 1, 2, 4, 5, 6
}
Prefer Functional Methods
For arrays, 映射, 筛选, and reduce are often clearer than a manual loop. Reach for a for loop only when you need early break or index-based logic that the functional methods cannot express cleanly.
示例代码
// for...of — the modern way to iterate arrays
const tasks = ["design", "code", "test", "deploy"];
for (const task of tasks) {
console.log(`→ ${task}`);
}
// Classic for loop when you need the index
const numbers = [10, 20, 30, 40, 50];
for (let i = 0; i < numbers.length; i++) {
console.log(`index ${i}: ${numbers[i]}`);
}
// while loop for conditional repetition
let retries = 0;
const maxRetries = 3;
while (retries < maxRetries) {
console.log(`Attempt ${retries + 1}`);
retries++;
}
// break and continue
const scores = [85, 42, 90, 30, 88, 95];
let passed = 0;
for (const score of scores) {
if (score < 60) continue; // skip failing scores
passed++;
if (passed >= 3) break; // stop after 3 passing scores
console.log("Passed:", score);
}
// for...in for object keys
const config = { host: "localhost", port: 3000, debug: true };
for (const key in config) {
console.log(`${key} = ${config[key]}`);
}
Demonstrates for...的 for 数组值, classic indexed for 循环, 虽然循环 for retries, break/continue 到筛选 and 停止 early, and for...in for 对象键.
动手试一试
- 文本计数器
Counting characters and words 是 classic 循环任务.
- 行 Deduplicator
移除 duplicates 需要 iterating and comparing 行.
常见错误
错误写法
Using for...in 到 iterate 数组
正确做法
for...in iterates over 属性键 (as 字符串) and 能包含 inherited 属性. Use for...的到 iterate 数组值, or classic for 循环如果你 需要索引.
错误写法
创建无限虽然循环通过 forgetting 到更新条件变量
正确做法
总是制作确定循环变量更改内部请求体所以条件 eventually becomes 假. Use safety 计数器 as backup for 复杂条件.
相关资源
相关速查表
- JavaScript Cheatsheet
循环语法 and iteration 模式引用.
练习 循环
10 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。