Javascript Arrays


John R. Williams and Abel Sanchez

Integer Arrays

Follow along yourself in the Chrome Console.
Arrays in Javascript can store any kind of object eg numbers, strings etc. Here we will just store integers for compactness. We will demonstrate only the most common commands we will use. In a later lesson we will come back and discuss arrays in much more detail.

Arrays are 'zero' based so the first slot is a[0], then a[1] etc. If there are N slots then the last slot is a[N-1]

'push' a number onto the end of an array. Increases array length.

'pop' a number from the end of an array. Alters array length.

'shift' a number from the beginning of an array. Alters array length.

'unshift' adds a number from the beginning of an array. Alters array length.

'sort' - sorts an array.

'reverse' - reverse sorts an array.

'indexOf' returns the index location of a number.

Concatenate 2 arrays into a single array.

'slice' a section out of the array - leaves the array the same.
slice(start_pos, upto_end_pos)

'splice' a section out of the array - mutilates the array.
splice(start_pos, number_to_cut_out)

It is often used to remove the first element. The array can then act like a 'queue' ie splice(0,1)

'splice' can also 'repair' an array by inserting elements.
splice(start_pos, 0, elements_to_be_inserted);

Active Learning

Download images & starter code


click on zip image above

THE END