Arrays are a powerful element of programming languages. They allow to store and manipulate data using one name and then accessing individual data with an index (number). You can imagine them as a container that holds many objects.
You may also imagine a postman distributing letters in one street with a certain name, distinguishing the individual addresses by the house numbers. The name of the street compares to the array name in programming, the index has the same meaning as the house number.
The image below summaries the key features of an array and also visualises how the indexing works to create, access and delete fields of an array.
You have several ways to access the elements of an array. The most common ways are ...
- You can use the array name with the index in brackets to set or get the content of one field, Burt also to add new items.
- You can use the push/pop methods to add or remove items at the end of the array.
- You can use the unshift/shift methods to add or remove items at the beginning of an array.
A full documentation on arrays can be found on the MDN website. It not only describes in words what the class and its methods are doing, but it also provides small editors with sample code you can modify and execute. For each method there are detailed descriptions accessible on the left side of the window (if your browser window is wide enough) with even more sample code to play with. Have a look.
The following screenshot shows how the push and pop methods are working.
- Please follow the instructions given here to launch the Development Console of your Chrome browser and then do the example with the push and pop methods by yourself.
- Next try to figure out how the unshift and shift methods are working. You can have a look at the MDS documentation first (you find at in the array section).
We will work extensively with the Array methods for making games, so getting familiar with them will be very helpful later.