循环
一句话解释
循环是 construct 那个 repeats 块的 code 多个次数, 要么 fixed 数字 or 直到条件是 met.
用大白话说
A loop lets you run the same block of code over and over without copying and pasting it. This is essential when you need to process every item in an array, repeat a calculation, or keep asking for input until the user gives a valid answer.
The two most common kinds are the for loop (repeat a known number of times) and the 虽然 loop (repeat until a condition becomes false). Most languages also offer a for...的 or foreach loop that walks through each element of a collection directly.
The danger with loops is the infinite loop — if the stopping condition is never met, the loop runs forever and freezes your program. Always make sure the loop can exit.
示例
// for loop — repeat 5 times
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// while loop — repeat until condition is false
let count = 3;
while (count > 0) {
console.log(count); // 3, 2, 1
count--;
} for 循环运行 fixed 数字的 次数. 虽然 循环运行直到它的条件 becomes 假.
常见混淆
容易混淆的对象: recursion
关键区别: 循环 repeats code using iteration (for/虽然); recursion repeats 通过函数 calling 它自己. 循环是 通常更多 efficient; recursion 能是 clearer for 树-structured problems.
相关术语
相关资源
相关课程
- 循环
学习 for, 虽然, and for...的循环
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。