Press key to advance. Zoom in/out: Ctrl or Command + +/-.

Basic JavaScript
Part 2: Arrays

Estelle Weyl

Arrays

var browsers = ['Safari', 'Chrome', 'Explorer', 'FireFox', 'Opera'];

var random = ['shoe',27,null,[42,17,19],Math.PI];

Easier (or harder) to read

var nincompoops = [ 'Rush Limbaugh',
                    'Sarah Palin',
                    'Glenn Beck',
                    'Rick Perry'];

Old school

var browsers = new Array('Safari', 'Chrome', 'Explorer', 'FireFox', 'Opera');

Arrays → zero indexed

arrayName[index]

First Item

nincompoops[0];

Last Item

nincompoops[nincompoops.length - 1];

Add item

nincompoops[nincompoops.length] = 'Donald Trump';

Array Methods: Adding Items

nincompoops[nincompoops.length] = 'Donald';

Add to end:

 nincompoops.push('Rick');
 nincompoops.push('Michelle', 'Newt', 'Mitt');

Add to beginning

nincompoops.unshift('Ron', 'Herman');

Adding in the middle (based on index)

nincompoops.splice(2,0,'Dick', 'George');
Note: 0 is # to delete

Array Methods: Deleting Items

Delete last item

var lastItem = nincompoops.pop();

Delete first item

var firstItem = nincompoops.shift();

Delete based on index

var deletedItem = nincompoops.splice(2,1);

Exercise

  • Create an array with 6 items.
  • Remove the 5th item.
  • Make the 5th item the first item.
  • Remove the last item.
  • Make the last item the 2nd item.
  • Remove the 3rd and 4th items. Make them the last two items.
  • What is the value of the 3rd item now?

Next

Go