Accessing elements and iterating an array
To access a specific position of the array, we can also use brackets, passing the index of the position we would like to access. For example, let's say we want to output all the elements from the daysOfWeek
array. To do so, we need to loop the array and print the elements, starting from index 0 as follows:
for (let i = 0; i < daysOfWeek.length; i++) {
console.log(`daysOfWeek[${i}]`, daysOfWeek[i]);
}
Let's look at another example. Suppose that we want to find out the first 20 numbers of the Fibonacci sequence. The first two numbers of the Fibonacci sequence are 1 and 2, and each subsequent number is the sum of the previous two numbers:
// Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
const fibonacci = []; // {1}
fibonacci[1] = 1; // {2}
fibonacci[2] = 1; // {3}
// create the fibonacci sequence starting from the 3rd element
for (let i = 3; i < 20; i++) {
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2]; // //{4}
}
//...