Home  >  Article  >  Web Front-end  >  How to use for loop in JavaScript

How to use for loop in JavaScript

WBOY
WBOYOriginal
2023-05-16 10:07:07929browse

JavaScript is a powerful programming language capable of many functions. One of the most basic loop structures is the for loop. It allows us to repeatedly execute a piece of code based on conditions, which is very suitable for scenarios where we need to repeatedly operate a collection of objects or traverse an array.

The for loop consists of the following three parts: loop initialization, loop condition, and loop increment. The syntax structure is as follows:

for (循环初始化; 循环条件; 循环增量) {
  // 循环执行的代码
}

Let’s take a detailed look at the function of each part:

  • Loop initialization: executed once before the start of the loop, usually used to initialize variables such as counters.
  • Loop condition: used to decide whether to continue executing the loop code. If the condition is true, continue the loop; if it is false, stop the loop.
  • Loop increment: Executed once after each loop ends, usually used to increment or decrement variables such as counters.

Next, let’s learn how to use the for loop through some examples.

1. Traverse an array

Let’s first look at an extremely common application scenario: traversing an array. The code is as follows:

let numbers = [1, 2, 3, 4, 5];

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

The above code defines an array numbers, and then uses a for loop to iterate through each element in the array. The loop condition i < numbers.length determines the conditions for the loop to be executed, and the increment operation i ensures that each loop will be incremented. In the loop body, we use the console.log function to print the value of each element.

2. Build a multiplication table

Next, we try to use a for loop to build a multiplication table. The code is as follows:

for (let i = 1; i <= 9; i++) {
  for (let j = 1; j <= i; j++) {
    document.write(`${j}x${i}=${i*j} `);
  }
  document.write('<br>');
}

There are two for loops nested in the code. The outer loop variable i represents the number of rows in the multiplication table, and the inner loop variable j represents the number of columns in each row. After each inner loop, we wrap the line to avoid outputting multiple products on the same line.

The above code implements a simple multiplication table, which is a good practice question for beginners.

3. Nested for loops to implement array summation

Next, let’s look at a slightly more complex example: using nested for loops to sum two-dimensional arrays . The code is as follows:

let arrays = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

let sum = 0;

for (let i = 0; i < arrays.length; i++) {
  for (let j = 0; j < arrays[i].length; j++) {
    sum += arrays[i][j];
  }
}

console.log(sum);

The above code defines a two-dimensional array arrays, and then uses a nested for loop to sum each element in the array. The outer loop variable i represents each row in the array, and the inner loop variable j represents the number of columns in each row. The sum operation sum = arrays[i][j] accumulates each element in the array. Finally, we print out the summation result console.log(sum).

4. Simulating AI in games

Finally, let’s look at an interesting example: using a for loop to simulate AI behavior in games. The code is as follows:

let enemyHealth = 100;
let playerAttack = [10, 15, 20, 25, 30];

for (let i = 0; i < playerAttack.length; i++) {
  let damage = Math.floor(Math.random() * playerAttack[i]);
  enemyHealth -= damage;
  
  if (damage > 0) {
    console.log(`玩家使用技能${i+1},对敌人造成了${damage}点伤害!敌人还剩余${enemyHealth}点生命值。`);
  } else {
    console.log(`玩家技能${i+1}未能命中敌人!敌人还剩余${enemyHealth}点生命值。`);
  }
  
  if (enemyHealth <= 0) {
    console.log('敌人被击败了!');
    break;
  }
}

The above code defines an enemy health value and an array playerAttack, which stores the player's attack power. Use a for loop to simulate the behavior of players using different skills to attack enemies in the game. In each cycle, we will generate random numbers to simulate the damage caused to the enemy after the skill hits, and print out the corresponding information according to the situation.

If the enemy's health is reduced to 0 or below, the game ends, and we use the break statement to force the end of the loop.

Through the above examples, we can see the flexible application of for loops in JavaScript. It can not only traverse arrays, build multiplication tables and other common operations, but also simulate AI behavior in games. By repeatedly practicing and using the for loop, you can better understand and master its mysteries and lay a solid foundation for your own programming journey.

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