Highlights
All Snippets
Top 100 Snippets
Librarians
gbCodeLib

By Language
VB6
JavaScript
Perl
HTML
SQL
Java
DOS

GBIC >> Source Code >> JavaScript >> Snippet

09 Arrays


Arrays are a built - in JavaScript object.  
Arrays are zero - based.

Create an array -----------------------------------------------
var X = new Array ()      // sets array of undefined length
var X = new Array (5)     // sets array to length of 5
var X = new Array (1,2,3,4,5)     // sets array to length of 5 and initializes the values
var colors = new Array ( "red" , "blue" , "green" , 1, 5, 8);   //note different types assigned in same array

Referencing an array element ------------------------
Use square brackets to refer to a specific index.  
var X = colors[0];

Arrays can also have string indexes --------------
var X = new Array ()
X[ "one" ) = 10
X[ "two" ) = 32
X[ "three" ] = 44

Y = X[ "one" ]     //reference array element with string index in two ways
or
Y = X.one      //notice the X ... dot ... one notation, where 'one' is the string index


Multidimensioned arrays ------------------------------------
Multidimensioned arrays are not directly supported.  Workaround is to assign an array as the element of an array :
part1 = new Array (1,2,3)
part2 = new Array (5,part1)

Then, access elements in the multidimensional array using a double bracket opertator :
part2[1][3]


Array Object Properties and Methods -------------------------------
Propertes :
 length  number of elements in the array
 prototype

Methods
 concat  concatenates an array on to an array
 reverse  reverse order of elements in an array
 slice  returns a subsection of an array
 sort  sorts elements in an array
 splice  inserts or removes elements from an array
 push  add element to end of an array
 pop    delete last element from an array
 unshift  add elements to front of an array
 shift  remove elements from front of an array
 join  concatenates all elements into one string
 toString converts elements to a string
 toSource converts elements to a string with square brackets