Home / Advanced JavaScript Tutorials / Creating dense arrays

 

 

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS

-Free applets
-Web Tutorials
-Link to Us!

- CSS Drive
- JavaScript Menus
- PHP Resources
- Hotels & Vacations
- Java Online Casinos
- Web hosting Search


Red_CurlyC035.gif (995 bytes) Example: Writing out the current date and time using dense arrays

A dense array excels over a normal one when it comes to initializing a rather large array with values upon declaration. In this section, we'll create a script that writes out the current date and time, in the following format:

Tuesday, July 28, 1998

The obvious task at hand is to first declare a series of variables that store the text "Monday", "Tuesday" etc and "January", "February", etc, since JavaScript is not human, and does not by default understand our calendar system. The remaining work is to match these text with the current date, and write it out.

The tedious part is the formal, and the perfect job for arrays to handle- dense arrays, to be precise:

var dayarray=new Array("Sunday","Monday","Tuesday",
"Wednesday","Thursday","Friday","Saturday")

var montharray=new Array("January","February","March","April","May",
"June","July","August","September","October","November","December")

The above code not only efficiently stores in the days of the week and months of the year values into two arrays, but allows us to directly use the JavaScript prebuilt functions date.getDay() and date.getMonth() as the index to reference the current date as represented by text, and write them out. Let's see just how this is done. The below shows the complete code that outputs the current date and time:

<script>
var mydate=new Date()
var year=mydate.getYear()

// year<2000, pad it with "19"
if (year<2000)
year="19"+year
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()

//if the current date is less than 10, pad it.
if (daym<10)
daym="0"+daym
var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday",

"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",

"July","August","September","October","November","December")
//write out the final results
document.write("<small><font color='000000' face='Arial'><b>"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+"</b></font></small>")
</script>


A code that may take a full page to write now has been reduced to one third, thanks to our buddy the dense array.

-Tutorial introduction
-Quick review of declaring a "normal" array
-Overview of declaring dense arrays
-Improvements to dense arrays in Netscape 3
-Example: Writing out the current date and time using dense arrays


End of tutorial

http://javascriptkit.com
Copyright © 1997-2005 JavaScript Kit. NO PART may be reproduced without author's permission.