First, let’s study the methods for defining an empty array.
First method to definition an array
The first method we analyze to define an empty array is the use of the Array () object.
This method follows the following syntax:
var photo = new Array();
So the photo variable is an array defined using the new constructor.
In this way the Array() object is exploited.
Second method to definition an array
You can also not use the new constructor to create an empty array, so you can also just write:
var photo = ;
We can put the data into an array with multiple methods.
First method to insert data in array
Following the first method, we can assign the elements directly within the round brackets of the Array () object.
var photo = new Array(“img1.jpg”,”img2.jpg”,…);
Second method to insert data in array
The second method is the most used when we need to initialize an array with predefined elements and allows you to insert each element separated by commas:
var photo = [“img1.jpg”, “img2.jpg”, …];
Alternatively, you can create an empty array and then assign the elements:
var photo = ;
Now let’s see how to read data from an array.
Populate an array with the days of the week and print all elements.
In this lesson we will see how to print the elements without using the for loop and the length property, the subject of the next lessons.
So we put the days of the week in an array named days.
var days = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”];
After considering that the first element has index 0 and the others to follow have an increasing index, we print each element simply in this way:
Here is the complete script:
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; console.log (days ); console.log (days ); console.log (days ); console.log (days ); console.log (days ); console.log (days ); console.log (days );
Of course, you can use a loop to read the entire array, but we will analyze it in the next lessons.