1. 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. arrayLength is the initial length of the array. You can access this value using the length property. elementn is a list of values for the array's elements. When this form is specified, the array is initalized with the specified values as its elements, and the array's length property is set to the number of arguments. The Array object has the following methods:
2. arrayObjectName = new Array([element0, element1, ..., elementn])
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". myArray
.
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"]
.
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 "", it 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)
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:
today = new Date().
Xmas95 = new Date("December 25, 1995 13:30:00")
. If you omit hours, minutes, or seconds, the value will be set to zero.
Xmas95 = new Date(95,11,25)
. A set of values for year, month, day, hour, minute, and seconds. For example, Xmas95 = new Date(95,11,25,9,30,0)
.
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 the epoch 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 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:
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)
IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995"))
<BODY ONLOAD="JSClock()">The <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:
<FORM NAME="clockForm">
The current time is <INPUT TYPE="text" NAME="digits" SIZE=12 VALUE="">
</FORM>
</BODY>
<HEAD>The 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:
<SCRIPT language="JavaScript">
<!--
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>
document.aform.digits.value = tempThis displays the time string in the document. The final statement in the function is a recursive call to JSClock:
id = setTimeout("JSClock()", 1000)The built-in JavaScript setTimeout function specifies a time delay to evaluate an expression, in this case a call to JSClock. The second argument indicates a 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).
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
. When using Function properties, functionObjectName is either the name of an existing Function object or a property of an existing object.
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 "function".
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 setBGColor shown above is similar to declaring the following function:
2. <INPUT NAME="colorButton" TYPE="button"
VALUE="Change background color"
onClick="setBGColor()">function setBGColor() {
Assigning a function to a variable is similar to declaring a function, but they have differences:
document.bgColor='antiquewhite'
}
var setBGColor = new Function("...")
, setBGColor is a variable for which the current value is a reference to the function created with new Function()
.
function setBGColor() {...}
, setBGColor is not a variable, it is the name of a function.
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. The following table summarizes Math's methods.
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 use these properties as follows:
biggestNum = Number.MAX_VALUE
The following table summarizes Number's properties.
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN
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 the reference topic for substring.
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")
The following table summarizes the methods of String objects:
isNaN(testValue)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()
}
parseFloat(str)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.