Objects
The predefined core objects are Array
, Boolean
, Date
, Function
, Math
, Number
, RegExp
, and String
.
Array Object
JavaScript does not have an explicit array data type. However, you can use the predefined Array
object and its methods to work with arrays in your applications. The Array
object has methods for manipulating arrays in various ways, such as joining, reversing, sorting them. It has a property for determining the array length and other properties for use with regular expressions.
An array is an ordered set of values that you refer to with a name and an index. For example, you could have an array called emp
that contains employees' names indexed by their employee number. So emp[1]
would be employee number one, emp[2]
employee number two, and so on.
To create an Array
object:
1. arrayObjectName = new Array([element0, element1, ..., elementN])
2. arrayObjectName = new Array([arrayLength])arrayObjectName
is either the name of a new object or a property of an existing object. When using Array
properties and methods, arrayObjectName
is either the name of an existing Array
object or a property of an existing object.
element0, element1, ..., element
N
is a list of values for the array's elements. When this form is specified, the array is initialized with the specified values as its elements, and the array's length
property is set to the number of arguments.
In Navigator 2.0 and Navigator 3.0, arrayLength
is the initial length of the array. In Navigator 4.0, if the <SCRIPT>
tag does not specify "JavaScript1.2"
as the value of the LANGUAGE
attribute, this is still true. However, if it does specify "JavaScript1.2",
then Array(arrayLength)
creates an array of length one with arrayLength
as its only element. That is, it no longer considers a single integer argument as a special case.
In Navigator 4.0, in addition to creating arrays using the Array
function constructor, you can also create them using object initializers, as described in "Using Object Initializers".
The Array
object has the following methods:
concat
joins two arrays and returns a new array.
join
joins all elements of an array into a string.
pop
removes the last element from an array and returns that element.
push
adds one or more elements to the end of an array and returns that last element added.
shift
removes the first element from an array and returns that element
slice
extracts a section of an array and returns a new array.
splice
adds and/or removes elements from an array.
sort
sorts the elements of an array.
unshift
adds one or more elements to the front of an array and returns the new length of the array.
myArray = new Array("Wind","Rain","Fire")
myArray.join()
returns "Wind,Rain,Fire"; myArray.reverse
transposes the array so that myArray[0]
is "Fire", myArray[1]
is "Rain", and myArray[2]
is "Wind". myArray.sort
sorts the array so that myArray[0]
is "Fire", myArray[1]
is "Rain", and myArray[2]
is "Wind".
emp[1] = "Casey Jones"You can also populate an array when you create it:
emp[2] = "Phil Lesh"
emp[3] = "August West"
myArray = new Array("Hello", myVar, 3.14159)The following code creates a two-dimensional array and displays the results.
a = new Array(4)This example displays the following results:
for (i=0; i < 4; i++) {
a[i] = new Array(4)
for (j=0; j < 4; j++) {
a[i][j] = "["+i+","+j+"]"
}
}
for (i=0; i < 4; i++) {
str = "Row "+i+":"
for (j=0; j < 4; j++) {
str += a[i][j]
}
document.write(str,"<p>")
}
Multidimensional array test
Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2][1,3]
Row 2:[2,0][2,1][2,2][2,3]
Row 3:[3,0][3,1][3,2][3,3]
myArray = new Array("Wind","Rain","Fire")You can then refer to the first element of the array as
myArray[0]
or myArray["Wind"]
.
regexp.exec
, string.match
, and string.replace
. For information on using arrays with regular expressions, see "Regular Expressions".
Boolean Object
Use the predefined Boolean
object when you need to convert a non-boolean value to a boolean value. You can use the Boolean
object any place JavaScript expects a primitive boolean value. JavaScript returns the primitive value of the Boolean
object by automatically invoking the valueOf
method.
To create a Boolean
object:
booleanObjectName = new Boolean(value)
booleanObjectName
is either the name of a new object or a property of an existing object. When using Boolean
properties, booleanObjectName
is either the name of an existing Boolean
object or a property of an existing object.
value
is the initial value of the Boolean
object. The value
is converted to a boolean value, if necessary. If value
is omitted or is 0, null
, false
, or the empty string "", the object has an initial value of false
. All other values, including the string "false" create an object with an initial value of true
.
The following examples create Boolean
objects:
bfalse = new Boolean(false)
btrue = new Boolean(true) Date Object
JavaScript does not have a date data type. However, you can use the Date
object and its methods to work with dates and times in your applications. The Date
object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.
NOTE: Currently, you cannot work with dates prior to January 1, 1970.To create a
Date
object:
dateObjectName = new Date([parameters])where
dateObjectName
is the name of the Date
object being created; it can be a new object or a property of an existing object.
The parameters
in the preceding syntax can be any of the following:
Date
object methods for handling dates and times fall into these broad categories:
Date
objects.
Date
objects.
Date
objects.
getDay
method that returns the day of the week, but no corresponding setDay
method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
For example, suppose you define the following date:
Xmas95 = new Date("December 25, 1995")Then
Xmas95.getMonth()
returns 11, and Xmas95.getYear()
returns 95.
The getTime
and setTime
methods are useful for comparing dates. The getTime
method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date
object.
For example, the following code displays the number of days left in the current year:
today = new Date()This example creates a
endYear = new Date("December 31, 1990") // Set day and month
endYear.setYear(today.getYear()) // Set year to this year
msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day
daysLeft = (endYear.getTime() - today.getTime()) / msPerDay
daysLeft = Math.round(daysLeft)
document.write("Number of days left in the year: " + daysLeft)
Date
object named today
that contains today's date. It then creates a Date
object named endYear
and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear,
using getTime
and rounding to a whole number of days.
The parse
method is useful for assigning values from date strings to existing Date
objects. For example, the following code uses parse
and setTime
to assign a date value to the IPOdate
object:
IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995"))
Date
: it displays a continuously-updated digital clock in an HTML text field. This is possible because you can dynamically change the contents of a text field with JavaScript (in contrast to ordinary text, which you cannot update without reloading the document). The display in Navigator is shown in Figure 11.1.
Figure 11.1 Digital clock example
<BODY>
of the document is:
<BODY onLoad="JSClock()">
The
<FORM NAME="clockForm">
The current time is <INPUT TYPE="text" NAME="digits" SIZE=12 VALUE="">
</FORM>
</BODY><BODY>
tag includes an onLoad
event handler. When the page loads, the event handler calls the function JSClock
, defined in the <HEAD>
. A form called clockForm
includes a single text field named digits, whose value is initially an empty string.
The <HEAD>
of the document defines JSClock
as follows:
<HEAD>
The
<SCRIPT language="JavaScript1.2">
<!--
function JSClock() {
var time = new Date()
var hour = time.getHours()
var minute = time.getMinutes()
var second = time.getSeconds()
var temp = "" + ((hour > 12) ? hour - 12 : hour)
temp += ((minute < 10) ? ":0" : ":") + minute
temp += ((second < 10) ? ":0" : ":") + second
temp += (hour >= 12) ? " P.M." : " A.M."
document.clockForm.digits.value = temp
id = setTimeout("JSClock()",1000)
}
//-->
</SCRIPT>
</HEAD>JSClock
function first creates a new Date
object called time
; since no arguments are given, time is created with the current date and time. Then calls to the getHours
, getMinutes
, and getSeconds
methods assign the value of the current hour, minute and seconds to hour
, minute
, and second
.
The next four statements build a string value based on the time. The first statement creates a variable temp
, assigning it a value using a conditional expression; if hour
is greater than 12, (hour
- 13), otherwise simply hour
.
The next statement appends a minute
value to temp
. If the value of minute
is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp
in the same way.
Finally, a conditional expression appends "PM" to temp
if hour
is 12 or greater; otherwise, it appends "AM" to temp
.
The next statement assigns the value of temp
to the text field:
document.aform.digits.value = temp
This displays the time string in the document.
The final statement in the function is a recursive call to JSClock
:
id = setTimeout("JSClock()", 1000)
The predefined JavaScript setTimeout
function specifies a time delay to evaluate an expression, in this case a call to JSClock
. The second argument indicates a delay of 1,000 milliseconds (one second). This updates the display of time
in the form at one-second intervals.
Note that the function returns a value (assigned to id
), used only as an identifier (which can be used by the clearTimeout
method to cancel the evaluation).
Function Object
The predefined Function
object specifies a string of JavaScript code to be compiled as a function.
To create a Function
object:
functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)
functionObjectName
is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror
.
arg1, arg2, ... argn
are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".
functionBody
is a string specifying the JavaScript code to be compiled as the function body.
Function
objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.
In addition to defining functions as described here, you can also use the function
statement, as described in the JavaScript Reference.
The following code assigns a function to the variable setBGColor
. This function sets the current document's background color.
var setBGColor = new Function("document.bgColor='antiquewhite'")
To call the Function
object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor
variable:
var colorChoice="antiquewhite"
You can assign the function to an event handler in either of the following ways:
if (colorChoice=="antiquewhite") {setBGColor()}1. document.form1.colorButton.onclick=setBGColor
Creating the variable
2. <INPUT NAME="colorButton" TYPE="button"
VALUE="Change background color"
onClick="setBGColor()">setBGColor
shown above is similar to declaring the following function:
function setBGColor() {
Assigning a function to a variable is similar to declaring a function, but there are differences:
document.bgColor='antiquewhite'
}
Math
object has properties and methods for mathematical constants and functions. For example, the Math
object's PI
property has the value of pi (3.141...), which you would use in an application as
Math.PISimilarly, standard mathematical functions are methods of
Math
. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)Note that all trigonometric methods of
Math
take arguments in radians.
Table 11.1 summarizes the Math
object's methods.
Unlike many other objects, you never create a Math
object of your own. You always use the predefined Math
object.
It is often convenient to use the with
statement when a section of code uses several math constants and methods, so you don't have to type "Math" repeatedly. For example,
with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
} Number Object
The Number
object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:
biggestNum = Number.MAX_VALUE
You always refer to a property of the predefined
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaNNumber
object as shown above, and not as a property of a Number
object you create yourself.
Table 11.2 summarizes the Number
object's properties.
Table 11.2 Properties of Number
RegExp Object
The RegExp
object lets you work with regular expressions. It is described in "Regular Expressions".
String Object
JavaScript does not have a string data type. However, you can use the String
object and its methods to work with strings in your applications. The String
object has a large number of methods for manipulating strings. It has one property for determining the string's length.
To create a String
object:
stringObjectName = new String(string)
stringObjectName
is the name of a new String
object.
string
is any string.
For example, the following statement creates a String
object called mystring
:
mystring = new String ("Hello, World!")
String literals are also String
objects; for example, the literal "Howdy" is a String
object.
A String
object has one property, length
, that indicates the number of characters in the string. So, using the previous example, the expression
x = mystring.length
assigns a value of 13 to x
, because "Hello, World!" has 13 characters.
A String
object has two types of methods: those that return a variation on the string itself, such as substring
and toUpperCase
, and those that return an HTML-formatted version of the string, such as bold
and link
.
For example, using the previous example, both mystring.toUpperCase()
and "hello, world!".toUpperCase()
return the string "HELLO, WORLD!".
The substring
method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, mystring.substring(4, 9)
returns the string "o, Wo." For more information, see String.substring
in the JavaScript Reference.
The String
object also has a number of methods for automatic HTML formatting, such as bold
to create boldface text and link
to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the link
method as follows:
mystring.link("http://www.helloworld.com")
Table 11.3 summarizes the methods of String
objects:
Functions
JavaScript has several "top-level" functions predefined in the language eval
, isNan
, Number
, String
, parseInt,
parseFloat
, escape
, unescape
, taint
, and untaint
. For more information on all of these functions, see the JavaScript Reference.
eval Function
The eval
function evaluates a string of JavaScript code without reference to a particular object. The syntax of eval
is:
eval(expr)
where expr
is a string to be evaluated.
If the string represents an expression, eval
evaluates the expression. If the argument represents one or more JavaScript statements, eval
performs the statements. Do not call eval
to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
isNaN Function
The isNaN
function evaluates an argument to determine if it is "NaN" (not a number). The syntax of isNaN
is:
isNaN(testValue)
where testValue
is the value you want to evaluate.
On platforms that support NaN, the parseFloat
and parseInt
functions return "NaN" when they evaluate a value that is not a number. isNaN
returns true if passed "NaN," and false otherwise.
The following code evaluates floatValue
to determine if it is a number and then calls a procedure accordingly:
floatValue=parseFloat(toFloat)
if (isNaN(floatValue)) {
notFloat()
} else {
isFloat()
} parseInt and parseFloat Functions
The two "parse" functions, parseInt
and parseFloat
, return a numeric value when given a string as an argument. For detailed descriptions and examples, see the JavaScript Reference. The syntax of parseFloat
is
parseFloat(str)
where parseFloat
parses its argument, the string str
, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).
The syntax of parseInt
is
parseInt(str [, radix])
parseInt
parses its first argument, the string str
, and attempts to return an integer of the specified radix
(base), indicated by the second, optional argument, radix
. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt
encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt
function truncates numbers to integer values.
Number and String Functions
The Number and String functions let you convert an object to a number or a string. The syntax of these functions is:
Number(objRef)
where
String(objRef)objRef
is an object reference.
The following example converts the Date
object to a readable string.
<SCRIPT>
This prints "Thu Aug 18 04:37:43 Pacific Daylight Time 1983."
D = new Date (430054663215);
document.write (String(D) +" <BR>");
</SCRIPT> escape and unescape Functions
The escape
and unescape
functions let you encode and decode strings. The escape
function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape
function returns the ASCII string for the specified value.
The syntax of these functions is:
escape(string)
These functions are used primarily with server-side JavaScript to encode and decode name/value pairs in URLs.
unescape(string) taint and untaint Functions
The taint
and untaint
functions are used for adding and removing data tainting in Navigator 3.0. Data tainting prevents other scripts from passing information that should be secure and private, such as directory structures or user session history. JavaScript cannot pass tainted values on to any server without the end user's permission.
For information on tainting, see Chapter 7, "JavaScript Security."
Last Updated: 11/26/97 09:25:58