Arrays are generally described as "list-like objects". They are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do extremely useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we have got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice while totaling all the prices together and printing out the total price at the bottom.
Arrays consist of square brackets and items that are separated by commas.
You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property.
Items in an array are numbered, starting from zero. This number is called the item's index. Therefore, the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index in the same way that you accessed the letters in a string.
This is fine if you know the index of an item, but what if you do not? You can find the index of a particular item using the indexOf()
method. This takes an item as an argument and returns the index, or -1 if the item was not found in the array.
To add one or more items to the end of an array, you can use push()
. Note that you need to include one or more items that you want to add to the end of your array.
To remove the last item from the array, use pop()
.
If you know the index of an item, you can remove it from the array using splice()
.
Frequently, you will want to access every item in the array. You can do this using the for
statement:
Occasionally, you will want to do the same thing to each item in an array, leaving you with an array that contains the changed items. You can do this using map()
.