在编程中,循环用于重复代码块。
例如,如果要显示一条消息100次,则可以使用循环。这只是一个简单的例子。使用循环可以实现更多目标。
本教程重点介绍JavaScript for
循环。您将在即将到来的教程中了解其他类型的循环。
JavaScript for循环
for循环的语法为:
for(initialExpression; condition; updateExpression) {
// for loop body
}
这里,
- initialExpression初始化和/或声明变量,并且仅执行一次。
- 条件被评估。
- 如果条件为
false
,则for
循环终止。 - 如果条件为
true
,则执行for
循环内的代码块。
- 如果条件为
- 当条件是updateExpression更新initialExpression的价值
true
。 - 再次评估条件 。此过程将继续,直到条件为
false
为止。
要了解有关条件的更多信息,请访问JavaScript比较和逻辑运算符。
示例1:显示文本五次
// program to display text 10 times
let n = 5;
// looping from i = 1 to 5
for (let i = 1; i <= n; i++) {
console.log(`I love JavaScript.`);
}
输出
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
该程序的工作原理如下。
Iteration | Variable | Condition: i <= n | Action |
---|---|---|---|
1st | i = 1 n = 5 |
true |
I love JavaScript. is printed. i is increased to 2. |
2nd | i = 2 n = 5 |
true |
I love JavaScript. is printed. i is increased to 3. |
3rd | i = 3 n = 5 |
true |
I love JavaScript. is printed. i is increased to 4. |
4th | i = 4 n = 5 |
true |
I love JavaScript. is printed. i is increased to 5. |
5th | i = 5 n = 5 |
true |
I love JavaScript. is printed. i is increased to 6. |
6th | i = 6 n = 5 |
false |
The loop is terminated. |
示例2:显示从1到5的数字
// program to display numbers from 1 to 5
let n = 5;
// looping from i = 1 to 5
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
console.log(i); // printing the value of i
}
输出
1
2
3
4
5
该程序的工作原理如下。
Iteration | Variable | Condition: i <= n | Action |
---|---|---|---|
1st | i = 1 n = 5 |
true |
1 is printed. i is increased to 2. |
2nd | i = 2 n = 5 |
true |
2 is printed. i is increased to 3. |
3rd | i = 3 n = 5 |
true |
3 is printed. i is increased to 4. |
4th | i = 4 n = 5 |
true |
4 is printed. i is increased to 5. |
5th | i = 5 n = 5 |
true |
5 is printed. i is increased to 6. |
6th | i = 6 n = 5 |
false |
The loop is terminated. |
示例3:显示n个自然数的总和
// program to display the sum of natural numbers
let sum = 0;
let n = 100
// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
console.log('sum:', sum);
输出
sum: 5050
在这里, sum的值最初为0 。然后,将for
循环从i = 1 to 100
迭代i = 1 to 100
。在每次迭代中,将i加到sum上,并将其值增加1 。
当i变为101时 ,测试条件为false
, 总和等于0 +1 + 2 + … + 100 。
上面的程序加上自然数的和也可以写成
// program to display the sum of n natural numbers
let sum = 0;
let n = 100;
// looping from i = n to 1
// in each iteration, i is decreased by 1
for(let i = n; i >= 1; i-- ) {
// adding i to sum in each iteration
sum += i; // sum = sum + i
}
console.log('sum:',sum);
该程序还提供与示例3相同的输出。您可以在编程中以多种不同的方式完成相同的任务。编程全部与逻辑有关。
尽管两种方法都是正确的,但是您应该尝试使代码更具可读性。
JavaScript Infinite for循环
如果for
循环中的测试条件始终为true
,则它将永远运行(直到内存已满)。例如,
// infinite for loop
for(let i = 1; i > 0; i++) {
// block of code
}
在以上程序中,条件始终为true
,然后将无限次运行代码。
在下一个教程中,您将学习while
和do...while
循环。