JavaScript: Arrays




To contact us



[
HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]

© 2002 - 2014 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)

  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/Javascript/JS_Array.html">
    Arrays </a>
    </table>
    </body>
    </html>




The Array Object

Introduction

The purpose of this tutorial is to introduce you to JavaScript Arrays. This tutorial assumes the reader has basic programming knowledge or is familiar with another programming language. In the programming languages I have worked with, the arrays contain one data type. Consider the following example that shows how to define and create an array in the C, C++, and Java programming languages. Assume that each array location has been initialized to a value of 5.

Definition and Creation Variable int Array float Array double Array
  
    int a = 5 ;

    int x[] ;
    x = new int[5] ;

    float y[] ;
    y = new float[5] ;

    double xx[] ;
    xx = new double[5] ;
  
   
| 5 |
+---+
  
| 5 |   <-- index 0
+---+
| 5 |   <-- index 1
+---+
| 5 |   <-- index 2
+---+
| 5 |   <-- index 3
+---+
| 5 |   <-- index 4
+---+
   
   
| 5 |   <-- index 0
+---+
| 5 |   <-- index 1
+---+
| 5 |   <-- index 2
+---+
| 5 |   <-- index 3
+---+
| 5 |   <-- index 4
+---+
   
   
| 5 |   <-- index 0
+---+
| 5 |   <-- index 1
+---+
| 5 |   <-- index 2
+---+
| 5 |   <-- index 3
+---+
| 5 |   <-- index 4
+---+
   
Figure 1: Array Definition and Creation


There are a few points that are being made by the depictions in Figure 1. Each array shown above:

  1. Can only contain one data type;
  2. Are of a fixed length as defined;
  3. Can be referenced by a variable name;
  4. Depict data that is stored in contiguous memory locations;
  5. Depict data that is stored and referenced in sequential order.
For those who have programming experience, Figure 1 does not provide any new news. Please note that the location referenced by the variable name "a" can contain only one piece of data at a time. The point being made is that the array can contain more than one piece of data at any point in time. Furthermore, if I were to code the example in Figure 2, I would get the following result.

   
 
      int a = 5 ;

      int x[] ;
      x = new int[5] ;

      float y[] ;
      y = new float[5] ;

      double xx[] ;
      xx = new double[5] ;
      y[0] = (float)5.5 ;
      x[0] = y[0] ;

COMPILE ERROR
"Demo.java": Error #: 355 : 
     possible loss of precision: float, 
      required: int at line 28, column 16

   
Figure 2: Mixed Data Type Storage


In languages like "C", "C++", and Java, code like
   
      y[0] = (float)5.5 ;
      x[0] = y[0] ;
   

is not allowed. The question is, "Is this code snippet allowed in JavaScript?" We will explore JavaScript arrays in the next section.

The Definition and Syntax for a JavaScript Array

When you think of a data structure, these structures may come to mind:

  • Arrays
  • Balanced trees
  • Binary search trees
  • Hash tables
  • Linked lists
  • Queues
  • Stacks
You may be surprised to discover that the array is the only data structure provided by JavaScript. How do we create a JavaScript array?

   
indicates the following name is associated with a variable
 |
 |    name of variable
 |      |
 V      V        
var myArray = new Array(5)  
               ^    ^
               |    |
               |    +<--- creates an array object of 5
               |          locations 
               |
               |
        tells JavaScript to
        allocate memory for 
        the array       
   
Figure 3: Creating a JavaScript Array


The first addressable location in an array is addressed with an index of zero. In Figure 1. the highest index is four, but the number of items contained in the array is five. The maximum number of items that can be contained in an array is known as the length of the array. The length of an array is always one more than the index of the last item in the array. Good programming practices suggest that the array object variable should be named something that indicates the type of the information it will contain. For example, if my array is intended to contain car model names, I might name it var carModels.

   
var carModels = new Array(5)  

carModels[0] = "Acura RL"     
carModels[1] = "Toyota Camry"   
carModels[2] = "Lexus GS350"    
carModels[3] = "Ford Explorer"     
carModels[4] = "Nissan Maxima"   
   
Figure 4: Creating carModel Array


Each piece of information is stored within the array object. In Figure 4, the elements occupy a single column and separate rows in the table. Another example of the use of arrays is shown below.

Date/Array Code Date/Array Code
Implementation
   
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
 
var flashing = false

   var nowDate  ;
   var monthNo ;
   var currentMonth ;
   var currentMonthday ;
   var currentYear  ;
   var months = new Array("January", "February", "March",
                     "April", "May", "June", "July",
                     "August", "September", "October", 
                     "November", "December", 12   );

function getCalendarDate()
{

   nowDate          = new Date();
   monthNo          = nowDate.getMonth();
   currentMonth     = months[monthNo];
   currentMonthday  = nowDate.getDate();
   currentYear      = nowDate.getYear();
   if(currentYear < 2000) { 
      currentYear = currentYear + 1900; 
   }
   var dateString = currentMonth +
                    ' ' +
                    currentMonthday +
                    ', ' +
                    currentYear;

   document.forms[0].thisDate.value = dateString
   //return dateString;
} // function getCalendarDate()

// calculate current time, determine flasher state,
// and insert time into status bar every second
function updateTime() {
	var nowDate     = new Date()
	var currentHour = nowDate.getHours()
	var currentMin  = nowDate.getMinutes()
	var currentTime = "" + ((currentHour > 12) ? 
                          currentHour - 12 : currentHour)
	currentTime += ((currentMin < 10) ? ":0" : ":") + 
                          currentMin
	currentTime  += (currentHour >= 12) ? " PM" : " AM"
	currentTime += ((flashing) ? " " : "*")
	flashing = !flashing
        document.forms[0].thisTime.value = currentTime

	// recursively call this function every second 
        //   to keep timer going
	timerID = setTimeout("updateTime()",1000)
}
 

</script>
</head>

<body onLoad="getCalendarDate(), updateTime()">
<FORM>
   
   Today's date is: 
   


The time is:
</FORM> </body> </html>






Today's date is:


The time is:
                                   
Figure 5: Creating Array for Months of the Year


You wi;; note that the first twelve elements in the months array are strings and the thirteenth element is numeric.

Array Methods

Method Description
chop() used to truncate the last character of a all strings that are part of an array.
 
var questions = new Array("Look out?", "Duck?", "Feint?" )
questions.chop()
 

Causes the values of questions to become:

Look out Duck Feint
concat() Joins two or more arrays and returns the result
  
var letters = ["a", "b", "c", "d", "e"];
var numbers = [1, 2, 3, 4, 5];

// the following shows the array created 
//   ["a", "b", "c", "d", "e", 1, 2, 3, 4, 5]; 
//   alpha and numeric are unchanged
var alphaNumeric = letters.concat(numbers);
 
grep(searchstring) Takes an array and returns those array element strings that contain matching strings. This method is not defined so it must be written and included in your code, using the prototype property.

 
words = new Array("limit", "lines", "finish",
                   "cinder", "In", "Out", "inward")
inwords = words.grep("in")

The array, inwords, will be:

lines, finish, cinder, inward
join(delimiter)
Puts all elements in the array into a string, separating each element with the specified delimiter.
 
planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )
var jplanets = planets.join(";")
 

The value of the string jplanets is:

 
Mercury;Venus;Earth;Mars;Jupiter;Saturn;Uranus;Neptune;Pluto
 
pop()
This method behaves like a LIFO (Last In First Out) function and removes and returns the last element of an array
 
planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )
var lastword = planets.pop()

 

The value of the string lastword is:

  Pluto
 
push(strings)
Adds one or more elements to the end of an array and returns the new length.
 
planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn" )

planets.push( "Uranus", "Neptune", "Pluto")

 

The array, planets, will be:

 "Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto"
 
reverse()
Reverses the order of elements in an array.
 
planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )
var rplanets = planets.reverse()
 

The value of the array rplanets is:

 
Pluto,Neptune,Uranus,Saturn,Jupiter,Mars,Earth,Venus,Mercury
 
shift()
Decreases array element size by one by shifting the first element (at index=0) off the array and returning it.
  planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )
word = planets.shift()
 

The shifted array, planets, will return:

 Mercury 
sort()
Sorts the array elements in dictionary order or using a compare function passed to the method.
  planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )
word = planets.splice(3, 2, "done", "On")
 

The value of planets becomes:

  Earth;Jupiter;Mars;Mercury;Neptune;Pluto;Saturn;Uranus;Venus
 
splice()
It is used to remove and/or add elements in an array.
arrayObject.splice(index, no._ToBeAdded, element1,.....,element_n)
Parameter Description
index Required. Specify location/index to add/remove elements. This must be a number
no._ToBeAdded Required Specify how many elements should be added/removed. Must be a number, but can be zero
element1 Optional. Specify a new element to add to the array
element_n Optional. Nth element to be added


In the example below, the element starting at element 2 is removed and replaced with the strings: "Lena" "Albert." The value returned are those values that are replaced.
 
planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )
var planets = planets.reverse()
 
planets1 = planets.splice(2, 2, "Lena", "Albert")

The value of planets becomes:

Mercury Venus Lena Albert Mars Jupiter Saturn Uranus Neptune Pluto

The value of planets1 is set to:

Earth  <--- This is the removed element.
split(deliimiter)
Splits a string using the delimiter and returns an array.
planets = new String("Mercury;Venus;Earth;Mars;Jupiter;Saturn;Uranus;Neptune;Pluto")
var splanets = planets.split(";")

The values in the array splanets is:


The first element is   Mercury
The second element is  Venus
The third element is   Earth
The fourth element is  Mars
The sixth element is   Saturn
The seventh element is Uranus
The eighth element is  Neptune
The ninth element is   Pluto
 
unshift() Places elements at the start of an array
planets = new Array("Mercury", "Venus", "Earth",
                   "Mars", "Jupiter", "Saturn", "Uranus",
                    "Neptune", "Pluto" )

var unplanets   = planets.unshift("Kai Jim")

The array, unplanets, will be:

 
10 <--- number elements in array
Kai Jim,Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Pluto
Figure 6: Array Methods










HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]


To contact us

© 2002 - 2014 All Rights Reserved Total Application Works