Arrays

An array is a single variable that holds multiple values.

 

Denoted by square brackets e.g. var myArray = [ ] ;

 

Can use array index to insert values:

 

var myArray[0] = 17 ;

var myArray[1] = 22 ;

var myArray[6] = "Two-dimensional infrared spectroscopy" ;

 

  • Values can be of mixed data types.
  • Accessed through the index
  • 0 based index

To get the value use the square brackets with the desired index number of the value required:

 

var test = myArray[6] ; //test now has the same value as myArray index 6

 

 

Shorthand, enter values separated by comma:

 

var myArr = [21, 45,"Electron-Vibration-Vibration"]; //automatically indexed from 0

 

Alternatively, you may see an array declared as follows:

 

var myArr = new Array(); //since arrays are objects this creates an array as an object

 

 

Since arrays are objects (with properties and methods) they have information that we can access. For instance to find the length of an array we could use the .length property:

 

var myArr = [2013, "March", "Start"] ;

document.write(myArr.length) ; //this would display 3

var reversedArr = myArr.reverse() ; //this new array now has the values reversed, equivalent to ["Start", "March", 2013] ;

 

Adding an item to an array

 

Simply specify the new index using the square bracket notation [N]. So assuming an array has 3 elements (starting from 0) the 4th element will be at index 3:

 

myArray[3] = 'new-item' ;

 

Alternatively, we can use the .length method of the array as the index of the last position:

 

myArray[myArray.length] = 'new-item' ;

 

Another approach is to use the .push() method with the new item within its parentheses:

 

myArray.push('new-item') ;

myArray.push('new-item-1', 'new-item-2', 'new-item-3') ;

 

All of the above approaches add the new item to the end of the array, whereas the .unshift() method allows the new item to be added to the front of the array:

 

myArray.unshift('new-item') ;

 

 

Deleting items from an array

 

To remove the last element from an array, use the .pop() method:

 

myArray.pop() ; //e.g. original array [0,1,2,3] results in [0,1,2]

 

Or, to remove the first element in an array, use the .shift() method:

 

myArray.shift() ; //e.g. original array [0,1,2,3] results in [1,2,3]

Leave a Reply