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:
Next, let’s learn how to use the for loop through some examples.
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 arraynumbers
, and then uses a for loop to iterate through each element in the array. The loop conditioni < numbers.length
determines the conditions for the loop to be executed, and the increment operationi
ensures that each loop will be incremented. In the loop body, we use theconsole.log
function to print the value of each element.
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('
'); }
There are two for loops nested in the code. The outer loop variablei
represents the number of rows in the multiplication table, and the inner loop variablej
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.
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 arrayarrays
, and then uses a nested for loop to sum each element in the array. The outer loop variablei
represents each row in the array, and the inner loop variablej
represents the number of columns in each row. The sum operationsum = arrays[i][j]
accumulates each element in the array. Finally, we print out the summation resultconsole.log(sum)
.
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 arrayplayerAttack
, 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 thebreak
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!