The following code shows a basic demonstration of arrays:
The variable is a special variable because it contains many values. Essentially, it’s a list of genres. The array(5) construct creates space in memory for five variables, all named genre.
Accessing array data
After you specify an array, you can work with the individual elements using square-bracket syntax. An integer identifies each element of the array. The index usually begins with.
genre = "flight simulation";
The preceding code assigns the text value “flight simulation” to the genre array variable at position 0.
After you store the data in the array, you can use the same square-bracket syntax to read the information.
alert ("I like " + genre + " games.");
finds element 4 of the genre array and includes it in an output message.
Using arrays with for loops
The main reason to use arrays is convenience. When you have a lot of information in an array, you can write code to work with the data quickly. Whenever you have an array of data, you commonly want to do something with each element in the array. Take a look at to see how you can do so:
Notice several things in this code:
The array called gameList. This array contains the names of some great freeware games.
A for loop steps through the array. Arrays and for loops are natural companions. The for loop steps through each element of the array.
The array’s length is used in the for loop condition. Rather than specifying the value 10, the array’s length property was used in the loop. This practice is good because the for loop automatically adjusts to the size of the array when you add or remove elements.
Do something with each element. Because goes from 0 to 9 (the array indices), you can easily print each value of the array. In this example, an output string was added to.
If you want to completely ruin your productivity, Google some of these game names. They’re absolutely incredible, and every one of them is free. It’s hard to beat that.