Using JavaScript's built-in objects

How to use JavaScript's built-in objects Date, Math, String, Array, and Object

1 2 Page 2
Page 2 of 2

Date Methods

getDateReturns the day of month of a specified date
getDayReturns the day of week of a specified date
getHoursReturns the hour of a specified date
getMinutesReturns the minutes of a specified date
getMonthReturns the month of a specified date
getSecondsReturns the seconds of a specified date
getTimeReturns the number of seconds between January 1, 1970 and specified date
getTimeZoneoffsetReturns the time zone offset in minutes for the current loca le
getYearReturns the year of specified date
parseReturns the number of milliseconds in a data since January 1, 1970, 00:00:00
setDateSets the date
setHoursSets the hours of a specified date
setMinutesSets the minutes of a specified date
setMonthSets the month of a specified date
setSecondsSets the seconds of a specified date
setTimeSets the time of a specified date
setYearSets the year of a specified date
toGMTStringConverts a date to a string using GMT conventions
toLocaleStringConverts a date to a string using locale conventions
toStringConverts the value of a Date object or current location object to a string
UTCConverts a comma-delimited date to the number of seconds since Jan 1, 1970 < /TD>

Creating arrays and objects

JavaScript supports two (currently) undocumented object constructors: Array and Object. Both do a similar job, but are used in different situations. In JavaScript, an array is really just an object, using numbers or associative names for the array elements. You can create new arrays and objects with either constructor, but for readability, you'll probably want to use the constructor that is most closely associated with your application. Use Array when creating an array; use Object when creating an object.

Let's tackle the Array constructor first.

In JavaScript you can create an array explicitly using your own constructor function. Here is a n example of a basic array constructor.

function makeArray(numElements) {
   this.length = numElements
   for (count = 1; count <= numElements; count++)
      this[count] = 0;
   return (this);
}

To define a new array, you call the makeArray function using the new statement. The following example creates an array with three elements, and fills them with data.

var myArray = new makeArray(3);
myArray[1] = "item 1";
myArray[2] = "item 2";
myArray[3] = "item 3";

Actually, JavaScript doesn't much care how you make your arrays. Though you can define the number of elements in the array, the makeArray function uses this value only to pre-load an initial value in the first three elements. (Element 0 contains the length of the array; element[0] is synonymous with the length property.) You can add additional elements at any time, even after the array has been created.

The Array object in JavaScript does the same work as the makeArray constructor function. You can use it to create a new array, then provide the data for each element in the usual manner. In Netscape 2.0, the Array object ignores any "length" or number of elements value you pass to it, so if you need to store the number of elements in the array, you must do so explicitly.

var myArray = new Array();
myArray[0] = 3;
myArray[1] = "item 1";
myArray[2] = "item 2";
myArray[3] = "item 3";

When the array is created, JavaScript merely creates an object for it, but doesn't fill any of the elements with an initial value. JavaScript returns null when you access an element of an array that has not been expressly defined. In the example above myArray[4] returns null, since element[4] is not defined.

In Atlas, the Array object accepts a length parameter, so you don't need to set the length separately. Merely pass the number of elements as a parameter of the Array() constructor; you may then refer to the length using the construct array_name.length. You can remove array elements by defining them with null, but the length property remains constant. You can, however, manually change the length property at any time yourself, simply by defining a new value for array_name.length. As in Netscape 2.0, undefined array elements contain a null value.

Object is a generic object constructor, and is borrowed from Java. However, JavaScript's Object is a much simplified version of the Java Object class. In Java, Object is used as a superclass, but in JavaScript, Object is used as a simplified means of creating new objects without providing an object constructor function. In JavaScript, an object constructor function is called with the new statement, and the function defines any properties or methods of the object. In the following simplified example, the calling statement instantiates a new object named myObject. The makeObject function creates the object, defining one property ("name") to it.

myObject = new makeObject ("my object");
 
function makeObject(name) {
        this.name = name;
        return (this);
}

The Object constructor saves you the trouble of making a constructor function, and is handy when you don't need or want to define methods and properties of the object when it is created, or when you want to define just one two properties. These following two lines replicate the example above:

myObject = new Object();
myObject.name = "my object";

You might use the Object constructor as a quick means to create an object. One such example is a , color database, which uses JavaScript as a miniature database. The database can consist of just one or two objects; separate properties of the objects contain the individual data items.

The following script uses JavaScript to built a small database lookup application. The Object constructor creates two objects: an index object and a data object. The index object is really an array with 10 elements; each element contains the name of a Netscape-supported color. The data object mirrors the sequence of the color names, and includes the equivalent hexadecimal value for that color -- the color aliceblue is f0f8ff, for example, and blanchedalmond is ffebcd. Note that the same database can be constructed using Array.

<HTML><HEAD>
<TITLE>Color Database</TITLE>
<SCRIPT LANGUAGE="JavaScript">
Idx = new Object();
Data = new Object();
 
Idx[0]=10
Idx[1]="aliceblue"
Idx[2]="antiquewhite"
Idx[3]="aqua"
Idx[4]="aquamarine"
Idx[5]="azure"
Idx[6]="beige"
Idx[7]="bisque"
Idx[8]="black"
Idx[9]="blanchedalmond"
Idx[10]="blue"
 
Data[1]="f0f8ff"
Data[2]="faebd7"
Data[3]="00ffff"
Data[4]="7fffd4"
Data[5]="f0ffff"
Data[6]="f5f5dc"
Data[7]="ffe4c4"
Data[8]="000000"
Data[9]="ffebcd"
Data[10]="0000ff"
 
function checkDatabase() {
        var Found = false;
        var Item = document.testform.color.value.toLowerCase();
        for (Count = 1; Count <= Idx[0]; Count++) {
                if (Item == Idx[Count]) {
                        Found = true;
                        alert ("The hex triplet for '" + Item + "' is #" +
                                Data[Count]);
                        break;
                }
        }
        if (! Found)
                alert ("Sorry, the color '" + Item +"' is not listed in the database.");
 
}
</SCRIPT>
<FORM NAME="testform" onSubmit="checkDatabase()">
Specify a color name, then click the "Find" button to see its hex triplet: <BR>
<INPUT TYPE="text" NAME="color" Value="" onClick=0> <P>
<INPUT TYPE="button" NAME="button" Value="Find" onClick="checkDatabase()">
</FORM>
</BODY></HTML>

JavaScript's associative arrays can come in handy when creating databases. Associative array names are synonymous with the object's property names. With this feature you can simplify the color database script by defining a single object -- named Idx -- for the colors. Then use the names of the colors as the property names, defined as Idx["colorname"]. Each property is assigned the equivalent hexadecimal color value. For example, the property Idx["aliceblue"] -- which is the functional equivalent to the syntax Idx.aliceblue -- is assigned the hex value f0f8ff.

In the revised color database example, the user types a color name, which doubles as a property name for the Idx object. An if expression determines whether the Idx object contains a property with that name. If the return value is "<undefined>" then no such property exists, and therefore the color is not listed in the database. If the value is something else, it is assumed to be the hex value of the specified color, and that value is displayed in an alert box.

<HTML>
<HEAD>
<TITLE>Another Color Database</TITLE>
<SCRIPT LANGUAGE="JavaScript">
Idx = new Object();
Idx["aliceblue"] = "f0f8ff"
Idx["antiquewhite"] ="faebd7"
Idx["aqua"] ="00ffff"
Idx["aquamarine"] ="7fffd4"
Idx["azure"] ="f0ffff"
Idx["beige"] ="f5f5dc"
Idx["bisque"] ="ffe4c4"
Idx["black"] ="000000"
Idx["blanchedalmond"] ="ffebcd"
Idx["blue"] ="0000ff"
 
function checkDatabase() {
        var Item = document.testform.color.value.toLowerCase();
        if ("" + Idx[Item] == "<undefined>")
                alert ("Sorry, the color '" + Item +"' is not listed in the database.");
 
        else
                alert (Idx[Item])
}
</SCRIPT>
<FORM NAME="testform" onSubmit="checkDatabase()">
Specify a color name, then click the "Find" button to see its hex triplet: <BR>
<INPUT TYPE="text" NAME="color" Value="" onClick=0> <P>
<INPUT TYPE="button" NAME="button" Value="Find" onClick="checkDatabase()">
</FORM>
</BODY></HTML>

Conclusion

At first blush, JavaScript's army of objects can be dizzying. But many of these objects are highly specialized, and seldom used in a the typical JavaScript application. JavaScript's built-in objects are a different breed. Because they do not depend on the content of any given page, JavaScript's built-in objects -- Date, Math, String, Array, and Object -- tend to be heavily used in most any script. Mastery of these objects goes a long way to writing the coolest JavaScript applications possible.

Gordon McComb is an author, consultant, and lecturer. He has written 50 books and over a thousand magazine articles during his 20 years as a professional writer. More than a million copies of his books are in print. Gordon also writes a weekly syndicated newspaper column on computers, reaching several million readers worldwide. Gordon's latest book is The JavaScript Sourcebook, forthcoming from Wiley Computer Publishing.
1 2 Page 2
Page 2 of 2