Iterating Arrays
Use loops to iterate an array in JavaScript.
We'll cover the following...
In this lesson, we will see how loops iterate arrays, where iterate means accessing elements in the array one by one.
Iterating single-dimensional arrays
To iterate a single dimension array, we design a loop that will index each element and terminate when the end is reached. Take for example the following array:
var arr = [ 10, 25, 7, 100, 20 ];
To iterate it, we start off with the first element (index 0
) and end at the last element (index 4
).
Notice a couple of things:
- The indexing starts from
0
. - The index in each iteration is incremented by one.
- The indexing stops at the last index, which is always one less than the length of the array.
With these observations in mind, use the for
loop to iterate arr
as shown below.
Press + to interact
var arr = [10, 25, 7, 100, 20]; // initialise arr// iterate array from start to endfor(var i = 0; i < arr.length; i++){console.log(arr[i]);}console.log("indexing complete");
In the above code, we use the for
loop to iterate the ...