A variable can only hold one value. This is where arrays come in.
An array is like a variable but with square brackets and commer separated list of values.
var warWords = ['fight', 'bombs', 'spitfire', 'chimpanzee', 'melons']
Like variable to use an array you simply drop the var and just write: warWords
In the console this will give:
Array(5) [ "fight", "bombs", "spitfire", "chimpanzee", "melons" ]
Another way is using new Array() like this:
let warWords = new Array('fight', 'bombs', 'spitfire', 'chimpanzee', 'melons');
However the first way is the preferred way.
If we want just one of the values from the array we can select it based on it's position in the array. This is known as it's index. To select the third value we use a 2 (because JS starts counting with a zero) in square brackets.
warWords[2]
returns "spitfire"
to the console.
If you want to know the index of a known value you type: warWords.indexOf('bombs');
Arrays can also hold arrays inside them:
var planes = [['cessna', 'apache', 'learjet'],['spitfire', 'hurricane', 'F16'],['Jumbo Jet', 'Boeing 757', 'Airbus']]
NOTE: each set of square brackets must still be separated by a comma.
To select an item the same square bracket notation is used to select the sub-array, then another square bracket is used to select the value within that array:
Typing planes[1][0]
gives "spitfire"
, the first (0) value in the second(2) array.
let floraSize = 'Trees are big';
floraSize.length;
will tell you how long the variable is. In this case 13 letters and spaces.
floraSize[4];
will tell you what the fifth letter is: "s"
Now lets create an array with sub arrays and see what happens.
let flora = [['oak', 'beech', 'elm'], ['roses', 'dasies', 'tulips'], ['beechrow', 'orange', 'pear']];
So flora.length;
will return 3
which is the number of arrays.
To access that last array: flora[flora.length -1];
will return the values of the last sub array: Array(3) [ "beechrow", "orange", "pear" ]
which is the number of arrays.
To access that last array: flora[flora.length -1][0];
will return the values of the last sub array: "beechrow"
, the first value in the last array.
method | What it does | Example |
---|---|---|
pop | removes last item | .pop() |
push | adds to array | push() |
slice | umm | slice() |
splice | umm | splce() |
shift | umm | shift() |
There are several methods to change array values.
myArray.pop()
will remove the last item.