Home > Web Front-end > JS Tutorial > body text

What are the loop structures in javascript?

下次还敢
Release: 2024-05-08 22:51:19
Original
544 people have browsed it

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>
Copy after login
  • 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>
Copy after login
  • 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>
Copy after login
  • 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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!