Home  >  Article  >  Web Front-end  >  What are the loop structures in javascript?

What are the loop structures in javascript?

下次还敢
下次还敢Original
2024-05-08 22:51:19595browse

There are three loop structures in JavaScript: for loop: repeatedly executes a block of code under given conditions for a known number of iterations. while loop: As long as the condition is true, the code block is executed repeatedly, used to perform iteration when the condition is met. do-while loop: Execute a block of code at least once, then check a condition and repeat the block of code as long as the condition is true.

What are the loop structures in javascript?

Loop Structure in JavaScript

In JavaScript, the loop structure allows us to repeat a block of code a specified number of times . There are three main loop structures in JavaScript:

1. for loop

The for loop uses the following syntax:

<code>for (let i = 0; i < n; i++) {
  // 代码块
}</code>
  • let i = 0: Declare a variable i and initialize it to 0.
  • i < n: Loop condition, the loop will continue when i is less than n.
  • i : After each iteration, i will be incremented by 1.

2. while loop

while loop uses the following syntax:

<code>while (condition) {
  // 代码块
}</code>
  • condition: loop condition, the loop will continue as long as the condition is true.

3. do-while loop

The do-while loop is similar to the while loop, but the code block is executed before the condition is checked. Its syntax is as follows:

<code>do {
  // 代码块
} while (condition);</code>
  • condition: Loop condition, the loop will end when the condition is false.

Example

for loop:Print numbers 1 to 10

<code class="javascript">for (let i = 1; i <= 10; i++) {
  console.log(i);
}</code>

while loop:Print a random number until it is greater than 5

<code class="javascript">let randomNumber = Math.random();
while (randomNumber <= 0.5) {
  randomNumber = Math.random();
}
console.log(randomNumber);</code>

do-while loop: Print the numbers 1 to 3 at least once

<code class="javascript">let i = 0;
do {
  i++;
  console.log(i);
} while (i < 3);</code>

The above is the detailed content of What are the loop structures in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn