Arrays
- Arrays are also a collection of variables. They used for lists of similar variables (i.e. a bunch of numbers, or images).
- Arrays are indexed. Supplying the index (typically a number) to the array will return the variable at that index.
- Array indexes start at zero (0), and progress upwards
- To get an item out of the array, use the square brackets and the index
Array Metaphor
- You could think of arrays as a filing cabinet…
- You can only put one item into each box, and you label them so you can find them with ease.
- The labels are the indexes of the cabinet / array
Making an Array
Getting a value out of an array
Write the square brackets, and inside the index you want.
Modifying the array
- Write the square brackets to get to what is stored in that index of the array
- Works just like a variable
Useful array properties and methods
- length: returns the number of elements in the array
- push(something): adds an element at index zero, pushes all others back
- pop(): takes a variable off the top of the array and returns it
- shift(something): adds an element at the very end of the array
- unshift(): takes a variable off the bottom of the array
- sort(): will sort the variables numerically or alphabetically
- splice(index, number): removes and returns (number) of elements from the array, starting at (index)
- toString(): Like number.toString. This returns a string of every entry in the array
Some array examples
Output This already This, array, already, has, some, content
Output This content Length: 4
Splitting strings
Its possible to make an array out of strings by splitting them
Example:
The data in splitStatement will be [ “some”, “dogs”, “have”, “two”, “teeth” ]
Yep, you can split on anything
‘Iterating’ through an array
Summing up items in an array
Searching Arrays
Parallel Arrays
- Storing data associated with each other in two different arrays
- Data at the same index in each array are assumed to be related.
- Here one array stores names, while the other stores employment
- In the example above, entry 0 in names is related to entry 0 in employment.
- So Stan is a Janitor, Lee is a cook, and Isolde is a Queen
- Can easily get all the data with a for loop