Arrays can also be iterated with the for
loop. Let's see how it's done. Let's say we have
an array like this:
let arr = [1, 2, 3, 4, 5];
Let's output the elements of this array in a loop:
for (let i = 0; i <= arr.length - 1; i++) {
console.log(arr[i]);
}
You can not subtract one from the array length, but use a non-strict comparison:
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Iterating over the array with the for
loop gives you more control over what happens.
For example, you can display elements not
from zero, but from the first:
for (let i = 1; i < arr.length; i++) {
console.log(arr[i]);
}
You can display elements in reverse order:
for (let i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
Print all the elements of the following array to the console:
let arr = ['a', 'b', 'c', 'd', 'e'];
Print to the console all the elements of the next array, excluding the zero and the last:
let arr = ['a', 'b', 'c', 'd', 'e'];
Print the elements of the following array to the console in reverse order:
let arr = ['a', 'b', 'c', 'd', 'e'];
Fix the error in the following code:
let arr = ['a', 'b', 'c', 'd', 'e'];
for (let i = 0; i <= arr.length; i++) {
console.log(arr[i]);
}