循环
for、while、for...of、for...in,以及如何 break 和 continue。
你将学到
- 经典 for 循环及其使用时机
- while 和 do...while 循环
- for...of 遍历可迭代值(数组、字符串)
- for...in 遍历对象键(以及为何要小心)
- 用 break 和 continue 控制循环流程
概念讲解
经典 for 循环
需要索引时使用:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
while 和 do...while
while 在每次迭代前检查条件。do...while 在后检查,所以循环体至少执行一次:
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
let n = 0;
do {
console.log("runs at least once");
} while (n > 0);
for...of——遍历值
for...of 遍历可迭代的值——数组、字符串、Map、Set。这是现代遍历集合的惯用方式:
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...in 遍历对象的可枚举属性键。它不适用于数组——会以字符串形式返回索引,并可能包含继承的属性:
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]); // "a" 1, "b" 2, "c" 3
}
// 不要对数组用 for...in!
const arr = [10, 20, 30];
for (const i in arr) {
console.log(i); // "0", "1", "2"——字符串,不是数字
}
规则:数组用 for...of(值),对象用 for...in(键)。
break 和 continue
break完全退出循环。continue跳过本次迭代剩余部分,进入下一次。
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // 跳过 3
if (i === 7) break; // 在 7 停止
console.log(i); // 0, 1, 2, 4, 5, 6
}
优先使用函数式方法
对数组而言,map、filter 和 reduce 往往比手动循环更清晰。只有需要提前 break 或基于索引的逻辑时,才使用 for 循环。
示例代码
// for...of——现代遍历数组的方式
const tasks = ["design", "code", "test", "deploy"];
for (const task of tasks) {
console.log(`→ ${task}`);
}
// 需要索引时用经典 for 循环
const numbers = [10, 20, 30, 40, 50];
for (let i = 0; i < numbers.length; i++) {
console.log(`index ${i}: ${numbers[i]}`);
}
// while 循环用于条件重复
let retries = 0;
const maxRetries = 3;
while (retries < maxRetries) {
console.log(`Attempt ${retries + 1}`);
retries++;
}
// break 和 continue
const scores = [85, 42, 90, 30, 88, 95];
let passed = 0;
for (const score of scores) {
if (score < 60) continue; // 跳过不及格
passed++;
if (passed >= 3) break; // 3 个及格后停止
console.log("Passed:", score);
}
// for...in 遍历对象键
const config = { host: "localhost", port: 3000, debug: true };
for (const key in config) {
console.log(`${key} = ${config[key]}`);
}
演示了 for...of 遍历数组值、带索引的经典 for、while 重试循环、break/continue 过滤和提前停止,以及 for...in 遍历对象键。
动手试一试
- Text Counter
统计字符和单词是经典的循环任务。
- Line Deduplicator
去重需要遍历并比较每一行。
常见错误
错误写法
用 for...in 遍历数组
正确做法
for...in 遍历的是属性键(字符串形式),还可能包含继承属性。遍历数组值用 for...of,需要索引用经典 for 循环。
错误写法
忘记更新条件变量导致 while 无限循环
正确做法
确保循环变量在循环体内变化,使条件最终为 false。复杂条件可用安全计数器作为后备。
相关资源
相关速查表
- JavaScript Cheatsheet
循环语法与遍历模式参考。
练习 循环
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。