Declaring and initializing arrays

by jenny on 16 March 2008 - 06:59pm in

These are identical declarations for an array:

var foo = new Array()
var bar = [] are these, which also initialize the array:

var foo = new Array('first', 'second', 'third')
var bar = ['first', 'second', 'third']

Both of the above are accessed like so:

alert(foo[0])  // alerts 'first'
alert(bar[0])  // alerts 'first'

An associative array (which is really an object in JS) is declared/initialized like so:

var bash = {
  first : 'value 1',
  second: 'value 2',
  third : 'value 3'

...and can be accessed in one of two ways:

alert(bash['first'])  // alerts 'value 1'
alert(bash.first)     // alerts 'value 1'