📜  js forloop - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:58.754000             🧑  作者: Mango

JavaScript For loop

When working with JavaScript, it is often necessary to perform a set of actions multiple times. This is typically achieved using loops, and one such loop in JavaScript is the for loop.

Syntax

The basic syntax of the for loop is as follows:

for (initialization; condition; increment/decrement) {
  // code block to be executed
}
  • initialization: this is executed once at the beginning of the loop, and typically initializes a variable that will be used in the loop.
  • condition: this is evaluated at the beginning of each iteration of the loop. If it returns true, the loop will continue; if it returns false, the loop will terminate.
  • increment/decrement: this is executed at the end of each iteration of the loop, and typically updates the variable initialized in the initialization.
  • code block to be executed: this is the code that will be executed each time the loop iterates.
Example

Let's say we want to loop through the elements of an array and print them to the console. We could do this using a for loop as follows:

const arr = ['apple', 'banana', 'cherry'];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

In this example, we initialize the variable i to 0, and set the condition to check if i is less than the length of the array arr. We then increment i by 1 at the end of each iteration. The code block simply prints the current element of the array to the console.

Nested For Loops

For loops can also be nested, which means that one loop is contained within another loop. This can be useful when working with multidimensional arrays or when you need to perform a set of actions for each combination of two variables.

for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(i, j);
  }
}

In this example, we have two for loops nested inside each other. The outer loop counts from 0 to 4, while the inner loop counts from 0 to 2. The console will output the combinations of i and j.

Conclusion

The for loop is a powerful tool for iterating through arrays, counting numbers, and performing a set of actions multiple times. With nested for loops, you can even create complex patterns or loop through multiple dimensions of data.