Primer on JavaScript Arrays
You can define an
array in JavaScript in two ways:
- with literal
values or
- using Array object
Defining an array
with literals is straight forward:
minArray =
[ ];
myArray = [ "elem0", "elem1" ];
myMizedArray = [ "elem0", 23, "elem2" ];
myOtherArray = ["elem0", , "elem2"];
Creating an array
using Array object is also straight forward. The following example creates
a small two-dimensional array:
myArray = new
Array(2);
myArray[0] = new Array("elem0", "elem1", "elem2");
myArray[1] = new Array("elem0", "elem1");
Like Java, JavaScript
does not have a build in capability to support multi-dimensional arrays.
However, since an element of the array may be an array in itself it
provides an even more flexible mechanism for array creation. You can
for example create a 2-dimensional array of varied length like above.
JavaScript also
supports associative arrays - arrays where elements can
be referenced by a string literal instead of an integer. So, the following
example is perfectly legitimate and displays two alert messages: "elem1"
and then "Sam":
myArray = ["elem0",
"elem1"];
myArray["some"] = "Sam";
alert(myArray[0]);
alert(myArray["some"]);
Associative array
is a very powerful feature. It basically provides capabilities of a
simple Hashtable where you can store attribute-value pairs.
Arrays also support
a few methods that can be called on them. These methods can be used
no matter how you created the array (with literals or Array object).
The Array object has the following methods:
- concat
joins two arrays and returns a new array.
- join
joins all elements of an array into a string.
- pop
removes the last element from an array and returns that element.
- push
adds one or more elements to the end of an array and returns that
last element added.
- reverse
transposes the elements of an array: the first array element becomes
the last and the last becomes the first.
- shift
removes the first element from an array and returns that element slice
extracts a section of an array and returns a new array.
- splice
adds and/or removes elements from an array.
- sort
sorts the elements of an array.
- unshift
adds one or more elements to the front of an array and returns the
new length of the array.
|