Richard's JavaScript Tutorials

Updated 07/18/14

Home
Animation
precachedImages
digitalClock
Object Tag (Audio)
Cookies.htm
Math_Object
Using CSS
The Style Object
Client_Info
customObject
functions
UsingArrays
comments
concatenation
documentwrite
ifelse
Loops
forms
Strings
variables

 

Using Arrays

This section will demonstrate the use of different kinds of arrays and array methods. An array is a set of related objects. I'll provide a demonstration below.


I'll create a simple array of sport types

<html><head><title>Sports Array</title>
</head><body>
<script type="text/javascript">
<!--
//The related objects are listed here at the creation of the array
var sports = new Array();
sports[0] = "Baseball"
sports[1] = "Basketball"
sports[2] = "Soccer"
sports[3] = "Golf"
sports[4] = "Football"

// Now you can call the array element,  sports[element number]
document.write(sports[4]);

//--></script></body></html>

The above script produces the following result

Untitled

Now we will try using a few Array methods the first one is the reverse method.

<body><script type="text/javascript"><!--

// Here is the array the numbers 1 through 5
var numbers =new Array ("1","2","3","4","5");
// The following array method will reverse the order of the array elements.
document.write(numbers.reverse());
//--></script></body>

The above script produces the following result:


  Now let's try another array method here we will try the array shift method which will a pop the first element from the sports array and returns it.

You can use the following code:

<script type="text/javascript">
<!--
var sports = new Array();
sports[0] = "Baseball"
sports[1] = "Basketball"
sports[2] = "Soccer"
sports[3] = "Golf"
sports[4] = "Football"
 

// Using the array pop method
document.write(sports.shift());
//--></script>

 


Now one more final array method using the same sports array above. Here we will use the array method join which will join a string with the specified string separator.

In this example we use the dash symbol ("-") as  the string separator. These array methods basically work the same, you use the arrayName.arrayMethod;  format. For example ( arrayName.join(); ) or for the array below


<script type="text/javascript">
<!--
var sports = new Array();
sports[0] = "Baseball"
sports[1] = "Basketball"
sports[2] = "Soccer"
sports[3] = "Golf"
sports[4] = "Football"

//Array name is sports and the array method used here is join()

document.write(sports.join("-"));
//-->
</script>

Now try creating your own JavaScript Array and use atleast one Array method. You can find a list of all the array methods at www.devguru.com

Home

This site was last updated 07/08/14