for loops · for 循环
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
中文
用 for 循环重复
- 循环把同一个代码块运行很多次,这样你就不用重复写。
for (let i = 1; i <= 5; i++) { ... }有三部分:起点i = 1、测试i <= 5、步进i++。
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
English
Build a running total
- Keep a variable outside the loop and add to it on every pass.
中文
累积一个总和
- 在循环外保留一个变量,每一轮都往里加。
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Explore · 探索
Trace the running total · 追踪累积的总和
A loop repeats its body. Step through the passes and watch total grow. · 循环重复执行循环体。一轮一轮走,看着 total 增长。
English
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
中文
注意
i <= 5在 5 之后才停;i < 5在 5 之前就停。选错就是经典的“差一”(off-by-one)错误。- 在循环之前把总和设为
0,不要放在循环里面。
English
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
中文
常见错误
for (let i = 0; i < n; i++)运行n次。- 用
let声明计数器,不要省略。
English
Now you try
- Use a
forloop. - Press Check answer to test it.
中文
现在轮到你
- 使用
for循环。 - 按检查答案来测试它。
Use a for loop to log the numbers 1 to · 到 5, one per line. · 用 for 循环打印数字 1 到 5,每行一个。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a for loop to add up 1 to · 到 10, then log the total (it is 55). · 用 for 循环把 1 到 10 加起来,然后打印总和(是 55)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · 用 for 循环打印偶数 2、4、6,每行一个(用 i += 2 每次加 2)。
Click Run to see the output here. · 点击“运行”查看此处输出。