Зміст курсу
JavaScript Data Structures
JavaScript Data Structures
for Loop
Array iteration is a crucial concept when working with arrays. It allows us to process each element in an array, perform operations, and make decisions based on their values. In this chapter, we will explore for
loop for iterating over arrays.
Syntax
The for
loop is a fundamental tool for iterating over an array element by element. It allows us to access each element in the array by element index. The syntax for a for
loop is as follows:
In this syntax:
let i = 0
initializes a loop counter variablei
to zero;i < array.length
defines the condition for the loop to continue. It will run as long asi
is less than the length of the array;i += 1
increments the loop counter after each iteration.
Example
Here's an example of using the for
loop to access and display the elements of the students
array:
const students = ["Brandon", "Mario", "Saul"]; for (let i = 0; i < students.length; i += 1) { console.log(students[i]); }
- Line 1: This line declares an array called students and initializes it with three strings, which represent the students' names. The array contains
"Brandon"
,"Mario"
, and"Saul"
; - Line 3: This line starts a for loop. It has three parts separated by semicolons:
let i = 0;
: This part initializes a variablei
and sets it to0
.i
is used as a loop counter;i < students.length;
: This part is the condition for the loop to continue. The loop will continue as long asi
is less than the length of thestudents
array;i += 1
: This part is the update statement, which increments the value ofi
by1
after each iteration.
- Line 4: Inside the
for
loop, this line uses theconsole.log()
function to log the value at the i-th index of thestudents
array. In the first iteration,i
is0
, so it logs the name at index0
, which is"Brandon"
. In the second iteration, it logs"Mario"
, and in the third iteration, it logs"Saul"
.
Дякуємо за ваш відгук!