<!-- SophiaKnows -->

JAVASCRIPT BASICS
Rev 4: December 2004

<  PART:   A · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9  >

 

7. Built-in Objects

JavaScript includes a number of built-in objects that assist developers in manipulating certain data types inlcuding, most notably: dates, arrays, strings and numbers.

Date() The JavaScript Date object is used to work with dates and time

Array() The JavaScript Array object is used to work with arrays of values and objects

String The JavaScript String object is used to manipulate strings of character data

Math The JavaScript Math object is used to calculate number values

7.1 Date()

The JavaScript Date object is used to work with dates and time

7.1.1 Syntax

An instance of the date object is created when it is assigned to a variable using the reserved words new

var variable-label=new Date([optional arguments])

The optional-arguments are one of several valid date time expressions. If no arguments are passed, the instance of Date() is initialized to local time:

var now=new Date()

7.1.1.1 Date By Calendar Terms

The instance of date can be assigned to a specific calendar date and time by including integers representing optionally, with increasing precision, from left to right:

var variable = new Date(year,month,date[,hours[,minutes[,seconds[,ms]]]])

year is a two or four digit representation of the year, month is an integer between 0 and 11 representing the order the month, and date is an integer between 1 and 31 representing the day of the month:

var variable=new Date(2001,0,1) // Jan 1, 2001
var variable=new Date(88,11,1,16) // Dec 1, 1988 4:00 pm

7.1.1.2 Date By Date String

The date object can be initialized to a particular date and time using one of several recognized quoted date string formats:

var variable=new Date("[datestring]")
var then=new Date("January 1, 2001")
var laterThatDay=new Date("January 1, 2001 12:24:00")

7.1.1.2 Date By Milleseconds

In addition, Date() can assigned to a specifice date and time using a thirteen term number value representing the number of milliseconds since Jan 1, 1970 00:00:00:

var variable=new Date(NNNNNNNNNNNNN)
var now=new Date() // current time

Note that this method is most useful in calculating relative dates. There are for instance 86400000 milliseconds in a calendar day (see Listing 7.1 below)

7.1.2 Properties

None

7.1.3 Methods

Date() Returns a Date object
getDate() Returns the date of a Date object (from 1-31)
getDay() Returns the day of a Date object (from 0-6)
getMonth() Returns the month of a Date object (from 0-11)
getFullYear() Returns the year of a Date object (four digits)
getYear() Returns the year of a Date object (from 0-99)
getHours() Returns the hour of a Date object (from 0-23)
getMinutes() Returns the minute of a Date object (from 0-59)
getSeconds() Returns the second of a Date object (from 0-59)
getMilliseconds() Returns the millisecond of a Date object (from 0-999)
getTime() Returns the number of milliseconds since midnight 1/1-1970
getTimezoneOffset() Returns the time difference between the user's computer and GMT
getUTCDate() Returns the date of a Date object in universal (UTC) time
getUTCDay() Returns the day of a Date object in universal time
getUTCMonth() Returns the month of a Date object in universal time
getUTCFullYear() Returns the four-digit year of a Date object in universal time
getUTCHours() Returns the hour of a Date object in universal time
getUTCMinutes() Returns the minutes of a Date object in universal time
getUTCSeconds() Returns the seconds of a Date object in universal time
getUTCMilliseconds() Returns the milliseconds of a Date object in universal time
toGMTString() Converts the Date object to a string, set to GMT time zone
toLocaleString() Converts the Date object to a string, set to the current time zone
toString() Converts the Date object to a string

Listing 7.1 Date()
var now=new Date();

function days_to_ms(n) {
    return(n*86400000);
    }

for(i=0;i<7;i++) {
    then = new Date( now.getTime() + days_to_ms(i) );
    document.write("<p>" + then.toLocaleString());
    document.write("<li>getDate:   " + then.getDate());
    document.write("<li>getDay:   " + then.getDay());
    document.write("<li>getMonth:   " + then.getMonth());
    document.write("<li>getYear:   " + then.getYear());
    document.write("<li>getFullYear:   " + then.getFullYear());
    document.write("</p>");
    }

 

7.2 Array()

The JavaScript Array object is used to work with arrays of values and objects

Syntax for creating indexed arrays was provided in Part 3 JavaScript Arrays along with examples of the sort() and reverse() methods. This listing reviews those basics and adds several additional widely supported methods.

7.2.2 Syntax

An instance of an array object is created using the key words new and Array()

var variable = new Array();

The developer may define initial members of the array as comma separated list of values included in the parenthesis of the Array() declaration:

var variable = new Array([value[,value[,value]]]);

The developer can declare an empty prototype to which members are later assigned using an indexed based syntax variable[n]=[value]:

var variable = new Array();

variable[0]=[value];
variable[1]=[value];
variable[2]=[value];

7.2.2 Properties

lengthReturns the number of members in the array

7.2.3 Methods

concat()Return two or more arrays as a new array
join([delimiter])Joins the elements of an array into a string separated by specified [delimiter]
reverse()Reverses the order of the elements in an array
slice(x[,y])Creates a new array from section x-y of an existing array
sort()Sorts the elements of an array from A-Z
toSource()Returns a string that represents the source code of the array
toString()Returns a string that represents the specified array and its elements

Listing 7.2 Array()

var students1=new Array("Jane","Tom","Mary","Anne","Ahmed");
var students2=new Array("Lisa","John","Mark","Karen","Pilar");

students1=students1.sort()
document.write("<p>"+students1.join(', '));

students1=students1.reverse()
document.write("<p>"+students1.join(', '));

var students_all=students1.concat(students2).sort();
document.write("<p>"+students_all.join(', '));

students_all=students_all.slice(0,3);
document.write("<p>"+students_all.join(', '));

 

7.3 String

The JavaScript String object is used to manipulate strings of character data

7.3.1 Syntax

String type data is initially assigned to a variable in the form of a quoted literal using a matched pair of either double or sing quotes ("[value]") ('[value]')

var variable="[cdata]";
var variable='[cdata]';

Single quotes may appear within double quotes (" 'example' ") and vice versa (' "example" ')

var variable="Say 'good night', Mary";
var variable='Say "good night", Mary';

Both single and double quotes can be escaped using the backslash (" \"example\" ") (' \'example\' ')

var variable="Say \"good night\", Mary";
var variable='Say \'good night\', Mary';

7.3.2 Properties

lengthReturns the number of characters in the string

7.3.2 Methods

anchor()Returns a string as an anchor
big()Returns a string in big text
bold()Returns a string in bold
charAt(index)Returns the character at a specified position
charCodeAt(i)Returns the Unicode of the character at a specified position
concat()Returns two concatenated strings
fixed()Returns a string as monospace text
fontcolor()Returns a string in a specified color
fontsize()Returns a string in a specified size
fromCharCode()Returns the character value of a Unicode
indexOf()Returns the first index of the specified characters, or -1 if unmatched
italics()Returns a string in italic
lastIndexOf()Returns the last index of the specified characters, or -1 if unmatched
link()Returns a string as a hyperlink
match()Returns the first index of the specified characters, or null if unmatched
replace()Replaces some specified characters with some new specified characters
search()Returns the index of the specified characters, or -1 if unmatched
slice()Returns a string containing a specified character index
small()Returns a string as small text
split()Splits a string into an array of strings
strike()Returns a string strikethrough
sub()Returns a string as subscript
substr()Returns the specified characters.
substring()Returns the specified characters.
sup()Returns a string as superscript
toLowerCase()Converts a string to lower case
toUpperCase()Converts a string to upper case

Listing 7.2 String
var string_1="Text String";

document.write("<p>" + string_1.big())  
document.write("<p>" + string_1.bold()) 
document.write("<p>" + string_1.fixed())    
document.write("<p>" + string_1.fontcolor('red'))    
document.write("<p>" + string_1.fontsize('3'))    
document.write("<p>" + string_1.italics())    
document.write("<p>" + string_1.link('#'))    
document.write("<p>" + string_1.small())    
document.write("<p>" + string_1.strike())    
document.write("<p>" + string_1.sub())      
document.write("<p>" + string_1.sup())    
document.write("<p>" + string_1.toLowerCase())    
document.write("<p>" + string_1.toUpperCase())   

 

7.4 Math

The JavaScript Math object is used to calculate number values

7.4.1 Properties

none

7.4.2 Methods

abs(x) Returns the absolute value of x
acos(x)Returns the arccosine of x
asin(x)Returns the arcsine of x
atan(x)Returns the arctangent of x
atan2(y,x)Returns the angle from the x axis to a point
ceil(x)Returns the nearest integer greater than or equal to x
cos(x)Returns the cosine of x
exp(x)Returns the value of E raised to the power of x
floor(x)Returns the nearest integer less than or equal to x
log(x)Returns the natural log of x
max(x,y)Returns the number with the highest value of x and y
min(x,y)Returns the number with the lowest value of x and y
pow(x,y)Returns the value of the number x raised to the power of y
random()Returns a random number between 0 and 1
round(x)Rounds x to the nearest integer
sin(x)Returns the sine of x
sqrt(x)Returns the square root of x
tan(x)Returns the tangent of x

 

Part 7 of 9 | Next Part 8: Built-in Methods >

<  PART:   A · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9  >

< CODEBASE | TOP^ | MAINPAGE >

Text & Design By Tony Pisarra
© SophiaKnows 1998-2004