Arrays![[next]](../../img/ltp/arrow-next.gif)
An array is a useful way of storing an ordered list of data.
|
1
2 3 4 5 6 7 8 9 10 11 var bands = [ "Fall Out Boy", "Usher", "Linkin Park", "Ne-yo", "Alicia Keys" ] printp("Favorite Bands:") print(bands) printp("My favorite band is: ", bands[0]) printp("My least favorite band is: ", bands[4]) |
Click to run the code. |
In this example, we create an array (bands) in lines 1-3; print the array in line 6; and print two different items that we extract from the array in lines 8-11.
Note the [ ] syntax (called "square brackets" or sometimes just "brackets") for creating an array. A list of values or variables inside brackets, separated by commas, becomes an array that can be stored in a variable.
Getting items from an array also uses brackets. Given that bands is an array, bands[0] is the first item, bands[1] is the second item, and so on. Because there are five items in the array, the last one is bands[4]. The number in brackets is called an "index".
Exercise: Arrays of arrays? Can one array be an item in another array? Try it! (An array made up of only other arrays is often called a "two-dimensional array".)
All arrays have a "property" called length representing the number of items. You can access this using the "." property accessor we talked about before, as in bands.length. Getting the length of an array can be really useful for generating the condition of a loop.
|
1
2 3 4 5 6 7 8 9 10 var bands = [ "Fall Out Boy", "Usher", "Linkin Park", "Ne-yo", "Alicia Keys" ] printp("There are ", bands.length, " bands.") for (var i = 0; i < bands.length; i++) { printp("Band ", i, ": ", bands[i]) } |
Click to run the code. |
Note that the above example uses i++ instead of i = i + 1 for the increment of the loop. Both statements are ways of increasing the value of i by 1.
Exercise: Reverse order looping. By changing only the for-loop parameters, print the bands array in reverse order, starting with "Alicia Keys", and ending with "Fall Out Boy".
Challenge: Reverse array. Write code that reverses the order of elements in the bands array.
Arrays are useful when you have a list of data, but what about when you have multiple pieces of data that describe a single thing? That's where objects come in, described in the next chapter.