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

How to use for loop in js

下次还敢
Release: 2024-05-06 13:06:15
Original
737 people have browsed it

The for loop in JavaScript is a loop structure used to repeatedly execute a block of code. It works through three phases: initialization, conditions, and increment, which are executed at the beginning of the loop, before it starts, and after it completes.

How to use for loop in js

Using for loop in JavaScript

The for loop is a method in JavaScript that is used to repeatedly execute a specific block of code. Loop structure. The syntax is as follows:

<code>for (initialization; condition; increment) {
  // 循环体:要重复执行的代码
}</code>
Copy after login

Working principle:

  1. Initialization (initialization): Executed once at the beginning of the loop. Usually used to declare variables or set initial values.
  2. condition (condition): Condition checked before each loop starts. If the condition is true, execute the loop body; otherwise, exit the loop.
  3. increment: Executed after each loop is completed. Typically used to increment or update loop variables.

Example:

<code class="javascript">// 循环 5 次
for (let i = 0; i < 5; i++) {
  console.log(`循环第 ${i + 1} 次`);
}

// 循环数组
const arr = [1, 2, 3, 4, 5];
for (let j = 0; j < arr.length; j++) {
  console.log(arr[j]);
}</code>
Copy after login

Other notes:

  • Initialization and increment statements can be omitted, But conditional statements are required.
  • The loop body can contain any JavaScript code.
  • You can use the break statement to exit the loop early.
  • You can use the continue statement to skip the current loop and continue executing the next loop.

The above is the detailed content of How to use for loop in js. 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