More on arrays

4. Arrays

This page is using the info on Free Code Camp. See also Understanding arrays by Tania Rascia

Variable lengths

You can get the length of a string variable by simply adding .length after it.

myVariableName.length

You can get find out what letter is in a certain position in the string by simply adding it’s place position in square brackets after it:

myVariable[5] will find the 6th letter of myVariable because Javascript starts counting with zero.

To find the last letter is a bit more convoluted: myVariable[myVariable.length -1]. Using -2 will find the second to last letter and so on. Using a positive integer here gives an error message.

Array Indexes

Link

Array indexes allow you to choose a specific value in an array. Again counting starts with a zero and the number is in square brackets

const dogs = [10, 20, 'greyhounds', 'border collies', 78]

To retrieve the fourth value: dogs[3]

These indexes can be used to change the data in an array (unlike variables which cannot be changed using indexes like this).

Our array for birds has an error: const birds = ['geese', 'ducks', 'coots', 'mice']

birds[birds.length -1] = 'swans' Now typing birds in the console will give:

Array(4) [ "geese", "ducks", "coots", "swans" ]

You can also create and access multi-dimensional arrays. This is an array with sub arrays inside it. For example:

const arr = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [[10,11,12], 13, 14]
    ];

So to select the number 2 here:

arr[0][1] The zero selects the first array and the [1] selects the second value which is 2.

To select the value 11 it would be: arr[3][0][1];

.push()

The function push() is used to add values to the end of an array.

So we have a reptile array: var reptiles = ['snakes', 'lizards', 'caiman']. To add something to the end of it:

reptiles.push('crocs'); Now reptiles will return:

Array(5) [ "snakes", "lizards", "caiman", "crocs" ]

Multiple values can be added at once. Just put them in the brackets and separate them with a comma. You can also add whole arrays to arrays. Just put them in square brackets:

reptiles.push(['lizards', 'toads'])

.pop()

.pop() does the opposite: it removes the last value in an array.