📅  最后修改于: 2023-12-03 15:00:49.954000             🧑  作者: Mango
A for
loop is a control flow statement that repeats a block of code a specified number of times. It consists of three parts: initialization, condition, and increment.
for (initialization; condition; increment) {
// code to be executed
}
initialization
statement is executed one time at the beginning of the loop.condition
statement is evaluated at the beginning of each iteration. If true
, the loop continues. If false
, the loop ends.increment
statement is executed at the end of each iteration.Suppose we want to print the numbers 1 to 5 using a for
loop.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
In this example:
initialization
statement sets the variable i
to 1
.condition
statement checks whether i
is less than or equal to 5
.increment
statement increases i
by 1
after each iteration.We can also use nested loops, which are loops within loops. Here is an example of a nested for
loop that prints a multiplication table:
for (let i = 1; i <= 10; i++) {
for (let j = 1; j <= 10; j++) {
console.log(`${i} x ${j} = ${i * j}`);
}
}
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
...
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
In this example, we have two for
loops:
The for
loop is a powerful construct in JavaScript that allows us to perform repetitive tasks with ease. By knowing how to use it, we can make our code more efficient and concise.