An array is a variable which can store many values inside it. A variable can only store one value. Those values can be accessed at any time using the arrayâ€™s index. The values stored within the array are called the members.
Creating an array
To create an array, declare a variable to hold values of the array, and declare the new Array object.
var navArray = new Array();
Alternately, you can also use a shorthand version, which will achieve the same outcome, where you wont have to declare the new array object.
var navArray = ;
Similar to variables, you can setup a new array and assign the values in one line by using shorthand. The variables can be a mix of numbers and strings.
var navArray = [â€œhomeâ€, â€œcatalogâ€, â€œabout-usâ€];
Accessing values in an array
To access the values that are now stored in the array, you use the arrayâ€™s index. The index starts at 0, so if you wanted to access the â€œcatalogâ€ string, you would write the following:
Add values to an array
You can add values to an array at any point since there are no restrictions . You do so by using the push method.
Remove values from an array
You can remove values from an array by using two different methods. If you would like to remove the last item from an array, you would use the pop method.
If you would like to add the value as the first item in the array, you would use the shift method.
Length of an array
A useful tool that you can use when working with arrays is the length property, which will show you how many elements are contained within your array.
var navArray = [â€œappleâ€, â€œpearâ€, â€œorangeâ€]; var navLength = navArray.length; alert(navLength);
Arrays always start at an index of 0 and the navLength variable in the proceeding example would return a value of 2 in the alert. In the following example, I am showing the index values of the navArray, so you can see how indexes are laid out.
navArray = â€œappleâ€; navArray = â€œpearâ€; navArray = â€œorangeâ€;