Section 5.5. Core Objects


5.5. Core Objects


Internet Explorer for Windows provides a direct portal between a web page and an ActiveX control (an automation object in Windows jargon) already registered with the Windows system. By creating an instance of the ActiveXObject, you supply your scripts with a reference to that control; use that reference to access the control's properties or invoke its methods. Uncovering the methods and properties of an automation object may require a bit of exploration through the Microsoft Developer Network web site (http://msdn.microsoft.com). A Microsoft utility, called OLE/COM Object Viewer, can also open doors for the persistent. A good place to start your exploration is http://msdn2.microsoft.com/en-us/library/7sw4ddf8.aspx. See also the GetObject( ) global function for a way to obtain a reference to an automation object via its local pathname.


Creating an ActiveXObject

 var myObj = new ActiveXObject(appName.className[, remoteServerName]) 


Properties

None.


Methods

None.


Every functionwhile it is executinghas an arguments object, which is accessible as a property of the function. The object is created automatically, and cannot be created outside of the function context that owns it. For example, consider a typical function definition:

 function myFunc( ) {      // function statements } 

A statement inside the function can access the arguments object by the following reference:

 arguments 

This object always contains the callee property, which is a reference to the very same function (explained in the callee property discussion). But you can also use the arguments object to access each parameter variable value through array notation. In the above example, a statement inside the myFunc( ) function can access the passed parameter value with the following reference:

 arguments[0] 

See the arguments property discussion of the Function object later in this chapter for practical applications.


Properties

callee
length

Methods

None.


Provides a reference to the function that created the arguments object. Thus, in an anonymous function, a statement can make a recursive call to the same (unnamed) function via the callee property, as shown in the Example.


Example

 myObj.doThis = function(input) {       // function statements that act on parameter value       if (!someCondition) {            // make recursive call to this anonymous function            arguments.callee(input);       } } 


Value

Function object reference.


Returns the number of arguments passed to the function in its current invocation. The number is not influenced by the number of parameter variables defined for the function.


Example

 function myFunc( ) {     for (var i = 0; i < arguments.length; i++) {         ...     } } 


Value

Integer.


An array is an ordered collection of one or more pieces of data. JavaScript array entries may be of any data type, and you can mix different data types in the same array. Each entry in an array has an index assigned to it. The default behavior is for the index to be a zero-based integer (the first entry has an index of zero). An index value may also be a string, but the string index acts like a property name of an array object, and does not influence the numeric indices (which is why string-indexed entries cannot be iterated via the array's length property, but can be iterated via a for-in loop). Separate sets of integer- and string-indexed items can coexist within the same array object.

Accessing an entry in an array requires the name of the array and the index in square brackets:

 cars[0] cars["Ford"] 

You may also create an array of arrays to simulate multidimensional arrays. A reference to an item in a two-dimensional array uses syntax as follows:

 myArray[x][y] 

The number of entries in a JavaScript array (its length) can vary over time. Therefore, you do not have to initialize an empty array to a specific size (nor is there any particular advantage to doing so). To add a new entry to an array of indeterminant length, assign the value to the next higher array index value:

 cars[cars.length] = "Bentley"; 

A shortcut array creation technique is available starting in IE 4 and Navigator 4, using square brackets to contain values in literal notation.


Creating an Array

 var myArray = new Array( ); var myArray = new Array(sizeInteger); var myArray = new Array(element0, element1, ..., elementN); var myArray = [element0, element1, ..., elementN]; 


Properties

constructor
length
prototype

Methods

concat( )
every( )
filter( )
forEach( )
indexOf( )
join( )
lastIndexOf( )
map( )
pop( )
push( )
reverse( )
shift( )
slice( )
some( )
sort( )
splice( )
toLocaleString( )
toString( )
unshift( )

This is a reference to the function that created the instance of an Array objectthe native Array( ) constructor function in browsers.


Example

 if (myVar.constructor == Array) {     // process native string } 


Value

Function object reference.


Provides a count of the number of numerically indexed entries stored in the array. If the constructor function used to create the array specified a preliminary length, the length property reflects that amount, even if data does not occupy every slot.


Example

 for (var i = 0; i < myArray.length; i++) {     ... } 


Value

Integer.


This is a property of the static Array object. Use the prototype property to assign new properties and methods to future instances of arrays created in the current document. For example, the following function creates a return-delimited list of elements in an array in reverse order:

 function formatAsList( ) {     var output = "";     for (var i = this.length - 1; i >= 0; i--) {         output += this[i] + "\n";     }     alert(output); } 

To give an array that power, assign this function reference to a prototype property whose name you want to use s the method to invoke this function:

 Array.prototype.showReverseList = formatAsList; 

If a script creates an array at this point:

 var stooges = new Array("Moe", "Larry", "Curly", "Shemp"); 

the new array has the showReverseList( ) method available to it. To invoke the method, the call is:

 stooges.showReverseList( ); 

You can add properties the same way. These allow you to attach information about the array (its creation time, for example) without disturbing the ordered sequence of array data. When a new document loads into the window or frame, the static Array object starts fresh again.


Example

 Array.prototype.created = ""; 


Value

Any data, including function references.


concat( item1[, item2[, ... itemN]])

Returns an array that combines the current array object with one or more array objects (or other values) specified as the method parameter(s):

 var combinedArray = myArray1.concat(myArray2, someValue); 

Neither of the original arrays is altered in the process.


Returned Value

An Array object.


Parameters


item1...itemN

Any JavaScript value, including another array.


every( functionRef[, thisObject])

Executes a function (callback) on each element of an array. The every( ) function returns true if all function invocations return true; if one function invocation returns false, the every( ) function halts further calls to the external function, and returns false.

Information about the array element is passed to the callback function via three parameters: the value of the element, the index of the element, and a reference to the array, as in the following example:

 function allNumbers(val, i, array) {     return (typeof val == "number"); } var myArray = [10, 100, 1000]; var result = myArray.every(allNumbers); // result is true for the array 

The callback function is allowed to modify the original array, which may, at times, impact further callback calls. Only the length of the array is fixed at the time every( ) is invoked, and each element is passed to the callback function with the value in force at the time the callback is made. If an element yet to be reached is deleted, its value is passed to the function as undefined.

If the callback function requires an object for the purposes of scope (i.e., so that a reference to this points to the correct object), you may pass a reference to that object as an optional second parameter (see forEach( ) for an example).


Returned Value

Boolean.


Parameters


functionRef

Reference to a function written to accept three parameters: array value, array index, and array reference. The function should return a Boolean value.


thisObject

An optional reference to an object whose scope is required by statements (using this) in the callback function.


filter( functionRef[, thisObject])

Executes a function (callback) on each element of an array and returns a new array of values that pass whatever test is performed in the callback function (by the callback function returning true for that value). The original array is not modified unless the callback function makes such changes.

Information about the array element is passed to the callback function via three parameters: the value of the element, the index of the element, and a reference to the array (see every( ) for an example). The function should return a Boolean value indicating whether or not the value is one that should be returned as an element of the new array returned by filter( ). Note that the returned array may be smaller than the original.

The callback function is allowed to modify the original array, which may, at times, impact further callback calls. Only the length of the array is fixed at the time filter( ) is invoked, and each element is passed to the callback function with the value in force at the time the callback is made. If an element yet to be reached is deleted, its value is passed to the function as undefined.

If the callback function requires an object for the purposes of scope (i.e., so that a reference to this points to the correct object), you may pass a reference to that object as an optional second parameter.


Returned Value

Array.


Parameters


functionRef

Reference to a function written to accept three parameters: array value, array index, and array reference. The function should return a Boolean value.


thisObject

An optional reference to an object whose scope is required by statements (using this) in the callback function.


forEach( functionRef[, thisObject])

Executes a function (callback) on each element of an array, without returning any value.

Information about the array element is passed to the callback function via three parameters: the value of one element through each iteration, the index of the element, and a reference to the array.

The callback function is allowed to modify the original array, which may, at times, impact further callback calls. Only the length of the array is fixed at the time forEach( ) is invoked, and each element is passed to the callback function with the value in force at the time the callback is made. If an element yet to be reached is deleted, its value is passed to the function as undefined.

If the callback function requires an object for the purposes of scope (i.e., so that a reference to this points to the correct object), you may pass a reference to that object as an optional second parameter. In the following example, the myObj object is passed as the second parameter to give proper scope for the doNumberTest( ) method to increment a value stored as an object property:

 var myObj = {     successCounter: 0,     doNumberTest: function(val) {         if (typeof val == "number") {             this.successCounter++;         }     },     report: function ( ) {         alert("Successful " + this.successCounter + " times!");     } }; var myArray = [10, "100", 1000]; myArray.forEach(myObj.doNumberTest, myObj); 

You can then invoke the myObj.report( ) method at any time to read the accumulated value of the myObj.successCounter value. In this example the value is incremented twice during each invocation of the forEach( ) method because two of the array's values are numbers.


Returned Value

None.


Parameters


functionRef

Reference to a function written to accept three parameters: array value, array index, and array reference. The function should not return a value.


thisObject

An optional reference to an object whose scope is required by statements (using this) in the callback function.


indexOf( searchElement[, fromIndex])

Returns an integer indicating the zero-based position within the array where the first instance of a search element is located. If the search element is not found in the array, the return value is -1. The search is always from start of the array to the end and is based on the JavaScript strict equality (===) operator, meaning that the match must consist of the value and data type to be successful. In effect, this method provides a shortcut to find the index within an array of a known valueor just to find out if a value is contained in an arraywithout having to write looping code that iterates through the array values.


Returned Value

Integer. Zero or greater if the search element is contained in the array; -1 if the search element is not in the array.


Parameters


searchElement

Any JavaScript value, including another array or DOM object.


fromIndex

An optional integer indicating the zero-based position within the array elements at which begin the search. A negative value is a count of positions from the end of the array (but the search always works its way toward the end).


join([" delimiterString"])

Returns a string consisting of a list of items (as strings) contained by an array. The delimiter character(s) between items is set by the parameter to the method. Note that an array's items are only those items that are accessible via an integer index. Items referenced via string index values are treated as properties of the array object, and are thus independent of integer indexed values (the two sets can coexist in a single array without conflict). The join( ) method works only with the integer-indexed items.


Returned Value

String.


Parameters


delimiterString

Any string of characters. Nonalphanumeric characters must use URL-encoded equivalents (%0D for carriage return). The default delimiter string is a comma character.


lastIndexOf( searchElement[, fromIndex])

Returns an integer indicating the zero-based position within the array where the first instance of search element is located when searched from the end of the array. If the search element is not found in the array, the return value is -1. The search is always from the end of the array to the beginning and is based on the JavaScript strict equality (===) operator, meaning that the match must consist of the value and data type to be successful. This method is just like indexOf( ) but searches the array in the opposite direction.


Returned Value

Integer. Zero or greater if the search element is contained in the array; -1 if the search element is not in the array.


Parameters


searchElement

Any JavaScript value, including another array or DOM object.


fromIndex

An optional integer indicating the zero-based position within the array elements at which begin the search. A negative value is a count of positions from the end of the array (but the search always works its way toward the beginning).


map( functionRef[, thisObject])

Executes a function (callback) on each element of an array and returns a new array of values that are returned by the callback function. The original array is not modified unless the callback function makes such changes.

Information about the array element is passed to the callback function via three parameters: the value of the element, the index of the element, and a reference to the array. The function should return a value, which then becomes an element of the new array returned by map( ), as in the following example:

 function makeStringy(val, i, array) {     return val.toString( ); } var myArray = [10, 100, 1000]; var newArray = myArray.map(makeStringy); 

The callback function is allowed to modify the original array, which may, at times, impact further callback calls. Only the length of the array is fixed at the time map( ) is invoked, and each element is passed to the callback function with the value in force at the time the callback is made. If an element yet to be reached is deleted, its value is passed to the function as undefined.

If the callback function requires an object for the purposes of scope (i.e., so that a reference to this points to the correct object), you may pass a reference to that object as an optional second parameter.


Returned Value

Array.


Parameters


functionRef

Reference to a function written to accept three parameters: array value, array index, and array reference. The function should return a value.


thisObject

An optional reference to an object whose scope is required by statements (using this) in the callback function.


Returns the value of the last item in an array and removes it from the array. The length of the array decreases by one.


Returned Value

Any JavaScript value.


Parameters

None.


push( item1[, item2[, ... itemN]])

Appends one or more items to the end of an array. The length of the array increases by one.


Returned Value

The length (integer) of the array after the push operation.


Parameters


item1...itemN

Comma-delimited list of one or more JavaScript values, including object references.


Reverses the order of items in the array and returns a copy of the array in the new order. Not only does the reverse( ) method rearrange the values in the array, but it also returns a copy of the reversed array.


Returned Value

An Array object.


Parameters

None.


Returns the value of the first item in an array and removes it from the array. The length of the array decreases by one.


Returned Value

Any JavaScript value.


Parameters

None.


slice( startIndex[, endIndex])

Returns an array that is a subset of contiguous items from the main array. Parameters determine where the selection begins and ends.


Returned Value

An Array object.


Parameters


startIndex

A zero-based integer of the first item of the subset from the current array.


endIndex

An optional zero-based integer of the last item of the subset from the current array. If omitted, the selection is made from the startIndex position to the end of the array.


some( functionRef[, thisObject])

Executes a function (callback) on each element of an array and returns TRue if the callback function returns TRue for any one element, or false if no invocations of the callback function return TRue.

Information about the array element is passed to the callback function via three parameters: the value of the element, the index of the element, and a reference to the array. The function should return a Boolean value.

The callback function is allowed to modify the original array, which may, at times, impact further callback calls. Only the length of the array is fixed at the time some( ) is invoked, and each element is passed to the callback function with the value in force at the time the callback is made. If an element yet to be reached is deleted, its value is passed to the function as undefined.

If the callback function requires an object for the purposes of scope (i.e., so that a reference to this points to the correct object), you may pass a reference to that object as an optional second parameter.


Returned Value

Boolean.


Parameters


functionRef

Reference to a function written to accept three parameters: array value, array index, and array reference. The function should return a Boolean value.


thisObject

An optional reference to an object whose scope is required by statements (using this) in the callback function.


sort([ compareFunction])

Sorts the values of the array either by the ASCII value of string versions of each array entry or according to a comparison function of your own design. The sort( ) method repeatedly invokes the comparison function, passing two values from the array. The comparison function should return an integer value, which is interpreted by the sort( ) function as follows.

Value

Meaning

<0

The second passed value should sort later than the first value.

0

The sort order of the two values should not change.

>0

The first passed value should sort later than the second value.


The following comparison function sorts values of an array in numerical (instead of ASCII) order:

 function doCompare(a, b) {     return a - b; } 

To sort an array by this function, the statement is:

 myArray.sort(doCompare); 

By the time the sort( ) method has completed its job, it has sent all values to the doCompare( ) function two values at a time and sorted the values on whether the first value is larger than the second (in the manner of a bubble sort).

If an array's elements consist of objects, you can sort by the property values of those objects. For example, the following sorting function places an array of employee objects in alphabetical order by values of the objects' age properties:

 function compareByAge(a, b) {     return a.age - b.age; } 

Not only does the sort( ) method rearrange the values in the array, but it also returns a copy of the sorted array.


Returned Value

An Array object, sorted according to sorting criteria.


Parameters


compareFunction

A reference to a function that receives two parameters and returns an integer result.


splice( startIndex, deleteCount[, item1[, item2[, ... itemN]]])

Removes zero or more contiguous items from within an array and, optionally, inserts new items in their places. The length of the array adjusts itself accordingly.


Returned Value

An Array object containing removed items.


Parameters


startIndex

A zero-based integer of the first item of the subset from the current array.


deleteCount

An integer denoting how many items from the startIndex position are to be removed from the array.


item1...itemN

Comma-delimited list of JavaScript values to be inserted into the array in place of removed items. The number of items does not have to equal deleteCount.


Returns a comma-delimited string of values, theoretically in a format tailored to the language and customs of the browser's default language. Implementation details vary with browser and data type. IE 5.5 and later converts numbers of all kinds to strings with two digits to the right of the decimal, but triggers an error for object references. Mozilla leaves integers in their original format and displays object references as [object objectType]. The ECMA standard leaves such interpretations up to the browser maker.


Returned Value

Comma-delimited string.


Parameters

None.


Returns a comma-delimited string of values, identical to using the Array.join( ) method with a comma parameter. All values are converted to some string equivalent, including objects ([object] in IE/Windows; [object objectType] in IE 5/Macintosh, Mozilla, and Safari).


Returned Value

Comma-delimited string.


Parameters

None.


unshift( item1[, item2[, ... itemN]])

Inserts one or more items at the beginning of an array. The length of the array increases by the number of items added, and the method returns the new length of the array.


Returned Value

Integer.


Parameters


item1...itemN

Comma-delimited list of one or more JavaScript values.


A Boolean object represents any value that evaluates to true or false. By and large, you don't have to worry about the Boolean object because the browsers automatically create such objects for you when you assign a TRue or false value to a variable. Quoted versions of these values are treated only as a string.


Creating a Boolean Object

 var myValue = new Boolean( ) ar myValue = new Boolean(BooleanValue); var myValue = BooleanValue; 


Properties

constructor
prototype

Methods

toString( )
valueOf( )

This is a reference to the function that created the instance of a Boolean objectthe native Boolean( ) constructor function in browsers.


Example

 if (myVar.constructor == Boolean) {     // process native string } 


Value

Function object reference.


This is a property of the static Boolean object. Use the prototype property to assign new properties and methods to future instances of a Boolean value created in the current document. See the Array.prototype property description for examples. There is little need to create new prototype properties or methods for the Boolean object.


Example

 Boolean.prototype.author = "DG"; 


Value

Any data, including function references.


Returns the object's value as a string data type. You don't need this method in practice, because the browsers automatically convert Boolean values to strings when they are needed for display in alert dialogs or in-document rendering.


Returned Value

"TRue" | "false"


Parameters

None.


Returns the object's value as a Boolean data type. You don't need this method when you create Boolean objects by simple value assignment.


Returned Value

Boolean value: true | false.


Parameters

None.


The Date object is a static object that generates instances by way of several constructor functions. Each instance of a Date object is a snapshot of the date and time, measured in milliseconds relative to zero hours on January 1, 1970. Negative millisecond values represent time before that date; positive values represent time since that date.

The typical way to work with dates is to generate a new instance of the Date object, either for now or for a specific date and time (past or future, using the client local time). Then use the myriad of available date methods to get or set components of that time (e.g., minutes, hours, date, month). Browsers internally store a date as the millisecond value at Coordinated Universal Time (UTC, which is essentially the same as Greenwich Mean Time, or GMT). When you ask a browser for a component of that time, it automatically converts the value to the local time zone of the browser based on the client computer's control panel setting for the clock and time zone. If the control panel is set incorrectly, time and date calculations may go awry.


Creating a Date Object

 var now = new Date( ) ar myDate = new Date("month dd, yyyy hh:mm:ss"); var myDate = new Date("month dd, yyyy"); var myDate = new Date(yy, mm, dd, hh, mm, ss); var myDate = new Date(yy, mm, dd); var myDate = new Date(milliseconds); 


Properties

constructor
prototype

Methods

geTDate( )
getday( )
getFullYear( )
getHours( )
getMilliseconds( )
getMinutes( )
getMonth( )
getSeconds( )
getTime( )
getTimezoneOffset( )
getUTCDate( )
getUTCDay( )
getUTCFullYear( )
getUTCHours( )
getUTCMilliseconds( )
getUTCMinutes( )
getUTCMonth( )
getUTCSeconds( )
getVarDate( )
getYear( )
parse( )
setDate( )
setFullYear( )
setHours( )
setMilliseconds( )
setMinutes( )
setMonth( )
setSeconds( )
setTime( )
setUTCDate( )
setUTCFullYear( )
setUTCHours( )
setUTCMilliseconds( )
setUTCMinutes( )
setUTCMonth( )
setUTCSeconds( )
setYear( )
toDateString( )
toGMTString( )
toLocaleDateString( )
toLocaleString( )
toLocaleTimeString( )
toString( )
toTimeString( )
toUTCString( )
UTC( )
valueOf( )

This is a reference to the function that created the instance of a Date objectthe native Date( ) constructor function in browsers.


Example

 if (myVar.constructor == Date) {     // process native string } 


Value

Function object reference.


This is a property of the static Date object. Use the prototype property to assign new properties and methods to future instances of a Date value created in the current document. See the Array.prototype property description for examples.


Example

 Date.prototype.author = "DG"; 


Value

Any data, including function references.


Returns the calendar date within the month specified by an instance of the Date object.


Returned Value

Integer between 1 and 31.


Parameters

None.


Returns an integer corresponding to a day of the week for the date specified by an instance of the Date object.


Returned Value

Integer between 0 and 6. Sunday is 0, Monday is 1, and Saturday is 6.


Parameters

None.


Returns all digits of the year for the date specified by an instance of the Date object.


Returned Value

Integer. Navigator 4 goes no lower than zero. Internet Explorer and other mainstream browsers return negative year values.


Parameters

None.


Returns a zero-based integer corresponding to the hours of the day for the date specified by an instance of the Date object. The 24-hour time system is used.


Returned Value

Integer between 0 and 23.


Parameters

None.


Returns a zero-based integer corresponding to the number of milliseconds past the seconds value of the date specified by an instance of the Date object.


Returned Value

Integer between 0 and 999.


Parameters

None.


Returns a zero-based integer corresponding to the minute value for the hour and date specified by an instance of the Date object.


Returned Value

Integer between 0 and 59.


Parameters

None.


Returns a zero-based integer corresponding to the month value for the date specified by an instance of the Date object. That this method's values are zero-based frequently confuses scripters at first.


Returned Value

Integer between 0 and 11. January is 0, February is 1, and December is 11.


Parameters

None.


Returns a zero-based integer corresponding to the seconds past the nearest full minute for the date specified by an instance of the Date object.


Returned Value

Integer between 0 and 59.


Parameters

None.


Returns a zero-based integer corresponding to the number of milliseconds since January 1, 1970, to the date specified by an instance of the Date object.


Returned Value

Integer.


Parameters

None.


Returns a zero-based integer corresponding to the number of minutes difference between GMT and the client computer's clock for an instance of the Date object. Time zones to the west of GMT are positive values; time zones to the east are negative values. Numerous bugs plagued this method in early browsers, especially Macintosh versions.


Returned Value

Integer between -720 and 720.


Parameters

None.


Returns the calendar date within the month specified by an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

Integer between 1 and 31.


Parameters

None.


Returns an integer corresponding to a day of the week for the date specified by an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

Integer between 0 and 6. Sunday is 0, Monday is 1, and Saturday is 6.


Parameters

None.


Returns all digits of the year for the date specified by an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

Integer. Navigator 4 goes no lower than zero. Internet Explorer and other mainstream browsers return negative year values.


Parameters

None.


Returns a zero-based integer corresponding to the hours of the day for the date specified by an instance of the Date object but in the UTC time stored internally by the browser. The 24-hour time system is used.


Returned Value

Integer between 0 and 23.


Parameters

None.


Returns a zero-based integer corresponding to the number of milliseconds past the seconds value of the date specified by an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

Integer between 0 and 999.


Parameters

None.


Returns a zero-based integer corresponding to the minute value for the hour and date specified by an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

Integer between 0 and 59.


Parameters

None.


Returns a zero-based integer corresponding to the month value for the date specified by an instance of the Date object but in the UTC time stored internally by the browser. That this method's values are zero-based frequently confuses scripters at first.


Returned Value

Integer between 0 and 11. January is 0, February is 1, and December is 11.


Parameters

None.


Returns a zero-based integer corresponding to the seconds value past the nearest full minute of the date specified by an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

Integer between 0 and 59.


Parameters

None.


Returns a date value in a format (called VT_DATE) suitable for a variety of Windows-oriented applications, such as ActiveX controls and VBScript. Not for use with JavaScript date calculations.


Returned Value

VT_DATE format value (not for JavaScript use).


Parameters

None.


Returns a number corresponding to the year of an instance of the Date object, but exhibits irregular behavior. In theory, the method should return the number of years the date object represents since 1900. This would produce a one- or two-digit value for all years between 1900 and 1999. However, when you reach 2000, the pattern fails. Instead of producing values starting with 100, the getYear( ) method, some browsers return the same four-digit value as getFullYear( ). For this reason, it is best to use getFullYear( ) whenever possible (but observe the browser compatibility for that method). Note that this method is not an ECMA-supported method, whereas getFullYear( ) is.


Returned Value

Integer between 0 and 99 for the years 1900 to 1999; four-digit integer starting with 2000 for some browsers, or a continuation (100+) for others.


Parameters

None.


parse(" dateString")

Static Date object method that returns the millisecond equivalent of the date specified as a string in the parameter.


Returned Value

Date in milliseconds.


Parameters


dateString

Any valid string format equivalent to that derived from a Date object. See toString( ), toGMTString( ), and toLocaleString( ) methods for sample formats.


setDate( dateInt)

Sets the date within the month for an instance of the Date object. If you specify a date beyond the end of the object's current month, the object recalculates the date in the succeeding month. For example, if a Date object is set to December 25, 2007, you can find out the calendar date 10 days later with the following construction:

 myDate.setDate(myDate.getDate( ) + 10); 

After this calculation, the value of myDate is the equivalent of January 4, 2008.


Returned Value

New date in milliseconds.


Parameters


dateInt

Date integer.


setFullYear( yearInt)

Assigns the year for an instance of the Date object.


Returned Value

New date in milliseconds.


Parameters


yearInt

Integer. Navigator 4 allows digits no lower than zero. Internet Explorer and other mainstream browsers allow negative year values.


setHours( hourInt)

Sets the hours of the day for an instance of the Date object. The 24-hour time system is used. If you specify an hour beyond the end of the object's current day, the object recalculates the time in the succeeding day(s).


Returned Value

New date in milliseconds.


Parameters


hourInt

Zero-based integer.


setMilliseconds( msInt)

Sets the number of milliseconds past the seconds value for an instance of the Date object.


Returned Value

New date in milliseconds.


Parameters


msInt

Zero-based integer of milliseconds.


setMinutes( minuteInt)

Sets the minute value for the hour and date of an instance of the Date object.


Returned Value

New date in milliseconds.


Parameters


minuteInt

Zero-based integer.


setMonth( monthInt)

Sets the month value for the date of an instance of the Date object. That this method's values are zero-based frequently confuses scripters at first.


Returned Value

New date in milliseconds.


Parameters


monthInt

Zero-based integer. January is 0, February is 1, and December is 11. Assigning higher values increases the object to the succeeding year.


setSeconds( secInt)

Sets the seconds value past the nearest full minute for an instance of the Date object.


Returned Value

New date in milliseconds.


Parameters


secInt

Zero-based integer.


setTime( msInt)

Sets an instance of the Date object to the number of milliseconds since January 1, 1970.


Returned Value

New date in milliseconds.


Parameters


msInt

Integer of milliseconds.


setUTCDate( dateInt)

Sets the date within the month of an instance of the Date object but in the UTC time stored internally by the browser. If you specify a date beyond the end of the object's current month, the object recalculates the date in the succeeding month. For this and all other setUTC... methods, Safari has Daylight Savings Time problems that were fixed in version 2.02.


Returned Value

New UTC date in milliseconds.


Parameters


dateInt

Integer.


setUTCFullYear( yearInt)

Sets all digits of the year for an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

New UTC date in milliseconds.


Parameters


yearInt

Integer. Navigator 4 allows values no lower than zero. Internet Explorer and NN 6 allow negative year values.


setUTCHours( hourInt)

Sets the hours of the day for an instance of the Date object but in the UTC time stored internally by the browser. The 24-hour time system is used.


Returned Value

New UTC date in milliseconds.


Parameters


hourInt

Zero-based integer.


setUTCMilliseconds( msInt)

Sets the number of milliseconds past the seconds value of an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

New UTC date in milliseconds.


Parameters


msInt

Zero-based integer.


setUTCMinutes( minuteInt)

Sets the minute value for the hour and date of an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

New UTC date in milliseconds.


Parameters


minuteInt

Zero-based integer.


setUTCMonth( monthInt)

Sets the month value for an instance of the Date object but in the UTC time stored internally by the browser. That this method's values are zero-based frequently confuses scripters at first.


Returned Value

New UTC date in milliseconds.


Parameters


monthInt

Zero-based integer. January is 0, February is 1, and December is 11. Assigning higher values increases the object to the succeeding year.


setUTCSeconds( secInt)

Sets the seconds value past the nearest full for an instance of the Date object but in the UTC time stored internally by the browser.


Returned Value

New UTC date in milliseconds.


Parameters


secInt

Zero-based integer.


setYear( yearInt)

Sets the year of an instance of a Date object. Use setFullYear( ) instead. Note that this method is not an ECMA-supported method, whereas setFullYear( ) is.


Returned Value

New date in milliseconds.


Parameters


yearInt

Four-digit (and sometimes two-digit) integers representing a year.


Returns a string consisting only of the date portion of an instance of a Date object. The precise format is under the control of the browser and language, but U.S. English versions of modern supporting browsers return values in the format Ddd Mmm dd yyyy.


Returned Value

String.


Parameters

None.


Returns a string version of the GMT value of a Date object instance in a standardized format. This method does not alter the original Date object. For use in newer browsers, the toUTCString( ) method is recommended in favor of toGMTString( ).


Returned Value

String in the following format: dayAbbrev, dd mmm yyyy hh:mm:ss GMT. For example:

 Mon 05 Aug 2002 02:33:22 GMT 


Parameters

None.


Returns a string consisting only of the date portion of an instance of a Date object. The precise format is under the control of the browser and language.


Returned Value

String in a variety of possible formats. Examples of U.S. versions of browsers include the following.

Platform

String value

Internet Explorer 7

Sunday, April 01, 2007

Mozilla/Win

Sunday, April 01, 2007

Mozilla/Mac

04/01/2007

Safari

April 1, 2007

Opera

4/1/2007



Parameters

None.


Returns a string version of the local time zone value of both the date and time from a Date object instance. The format may be localized for a particular country or an operating system's convention.


Returned Value

String in a variety of possible formats. Examples of U.S. versions of browsers include the following.

Platform

String value

Internet Explorer 7

Sunday, April 01, 2007 10:30:00 AM

Mozilla/Win

Sunday, April 01, 2007 10:30:00 AM

Mozilla/Mac

Sun Apr 1 10:30:00 2007

Safari

April 1, 2007 10:30:00 AM PDT

Opera

4/1/2007 10:30:00 AM



Parameters

None.


Returns a string consisting only of the time portion of an instance of a Date object. The precise format is under the control of the browser and language.


Returned Value

String in a variety of possible formats. Examples of U.S. versions of browsers include the following.

Platform

String value

Internet Explorer 7

10:30:00 AM

Mozilla/Win

10:30:00 AM

Mozilla/Mac

10:30:00

Safari

10:30:00 AM PDT

Opera

10:30:00 AM



Parameters

None.


This is a method used mostly by the browser itself to obtain a string version of an instance of a Date object when needed for display in dialog boxes or on-screen rendering.


Returned Value

String in a variety of possible formats. Here are examples for U.S. versions of browsers.

Platform

String value

Internet Explorer 7

Sun Apr 1 10:30:00 PDT 2007

Mozilla/Win

Sun Apr 01 2007 10:30:00 GMT-0700 (Pacific Daylight Time)

Mozilla/Mac

Sun Apr 01 2007 10:30:00 GMT-0700 (PDT)

Safari

Sun Apr 01 2007 10:30:00 GMT-0700

Opera

Sun, 01 Apr 2007 10:30:00 GMT-0700



Parameters

None.


Returns a string consisting only of the time portion of an instance of a Date object. The precise format is under the control of the browser and language.


Returned Value

Platform

String value

Internet Explorer 7

10:30:00 PDT

Mozilla/Win

10:30:00 GMT-0700 (Pacific Daylight Time)

Mozilla/Mac

10:30:00 GMT-0700 (PDT)

Safari

10:30:00 GMT-0700

Opera

10:30:00 GMT-0700



Parameters

None.


Returns a string version of the UTC value of a Date object instance in a standardized format. This method does not alter the original Date object. For use in newer browsers, the toUTCString( ) method is recommended in favor of toGMTString( ).


Returned Value

String in the following format: dayAbbrev dd mmm yyyy hh:mm:ss GMT. For example:

 Mon 05 Aug 2002 02:33:22 GMT 


Parameters

None.


Date.UTC( yyyy, mm, dd[, hh[, mm[, ss[, msecs]]]])

This is a static method of the Date object that returns a numeric version of the date as stored internally by the browser for a Date object. Unlike parameters to the Date object constructor, the parameter values for the UTC( ) method must be in UTC time for the returned value to be accurate. This method does not generate a date object, as the Date object constructor does.


Returned Value

Integer of the UTC millisecond value of the date specified as parameters.


Parameters


yyyy

Four-digit year value.


mm

Two-digit month number (011).


dd

Two-digit date number (131).


hh

Optional two-digit hour number in 24-hour time (023).


mm

Optional two-digit minute number (059).


ss

Optional two-digit second number (059).


msec

Optional milliseconds past the last whole second (0999).


Returns the object's value.


Returned Value

Integer millisecond count.


Parameters

None.


If an ActiveX control property or method returns a collection of values, the usual JavaScript approach to collections (treating them as arrays) does not work for such values. The Enumerator object gives JavaScript a way to reference items in such collections by controlling a pointer to the list of items. For additional details, visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsobjenumerator.asp.


Creating an Enumerator

 var myEnumObj = new Enumerator(externalCollection); 


Properties

None.


Methods

atEnd( )
item( )
moveFirst( )
moveNext( )

Returns Boolean true if the Enumerator is pointing at the last item in the collection.


Returned Value

Boolean value: TRue | false.


Parameters

None.


Returns a value from the collection at the pointer's current position.


Returned Value

Number, string, or other value from the collection.


Parameters

None.


Adjust the location of the pointer within the collection, jumping to the first item in the collection, or ahead by one item.


Returned Value

None.


Parameters

None.


Browsers that implement TRy-catch exception handling automatically create an instance of the Error object whenever an error occurs during script processing. You can also create an Error object instance that you explicitly throw. The catch portion of the TRy-catch construction receives the Error object instance as a parameter, which scripts can examine to learn the details of the error, as exposed by the object's properties.


Creating an Error Object

 var myError = new Error("errorMessage"); 


Properties

constructor
description
fileName
lineNumber
message
name
number
prototype

Methods

toString( )

Provides a reference to the function that created the instance of an Error objectthe native Error( ) constructor function in browsers.


Example

 if (myVar.constructor == Error) {     // process native string } 


Value

Function object reference.


Provides a plain-language description of the error, frequently the same as appears in the IE script error dialog. Use the newer message property if possible.


Example

 if (myError.description.indexOf("Object expected") != -1) {     // handle "object expected" error } 


Value

String.


Specifies the URL of the page in which the script error occurred. This information appears in the Mozilla JavaScript/Error Console window for each reported error.


Example

 var sourceFile = myError.fileName; 


Value

URL string.


Specifies the number of the line in the source code where the current script error occurred. This information appears in the Mozilla JavaScript/Error Console window for each reported error.


Example

 var errorLine = myError.lineNumber; 


Value

Number in string format.


Provides a plain-language description of the error. There is no standard for the format or content of such messages.


Example

 if (myError.message.indexOf("defined") != -1) {     // handle error for something being undefined } 


Value

String.


This is a string that sometimes indicates the type of the current error. The default value of this property is Error. But the browser may also report types EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, and, if supported by the browser, a specific W3C DOM error type.


Example

 if (myError.name == "SyntaxError") {     // handle syntax error } 


Value

String.


Provides a number corresponding to an IE error. You must apply binary arithmetic to the value to derive a meaningful number. Use:

 var errNum = ErrObj.number & 0xFFFF; 

Then compare the result against Microsoft's numbered listing at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsmscRunTimeErrors.asp.


Example

 var errNo = myError.number; 


Value

Number.


This is a property of the static Error object. Use the prototype property to assign new properties and methods to future instances of a Error object created in the current document. See the Array.prototype property description for examples.


Example

 Error.prototype.custom = true; 


Value

Any data, including function references.


Provides a list of functions and possibly an event whose execution led to the error. For each trace back to a function, the stack entry notes the source code line number. This property can be a helpful debugging tool.


Value

Multi-line string.


Returns a string representation of the object, but the values differ between browser families. IE returns [object Error], while Mozilla returns a concatenation of the name and message properties.


Returned Value

String.


Parameters

None.


A function is a group of one or more script statements that can be invoked at any time during or after the loading of a page. Invoking a function requires nothing more than including the function name with a trailing set of parentheses inside another script statement or as a value assigned to an event handler attribute in an HTML tag.


Since the first scriptable browsers, a function is created by the act of defining it with a name inside a script element:

 function funcName( ) {...} 

More recent browsers also allow the use of two types of constructors, as shown below in "Creating a Function." These so-called anonymous functions (i.e., they have no names to reference) are especially useful when a property assignment requires a reference to a function, but you don't want to clutter your variable naming space with a function definition's name.

Functions may be built to receive zero or more parameters. Parameters are assigned to comma-delimited parameter variables defined in the parentheses pair following the function name:

 function doSomething(param1, param2, ... paramN) {...} 

A parameter value may be any JavaScript data type, including object references and arrays. There is no penalty for not supplying the same number of parameters to the function as are defined for the function. The function object receives all parameters into an array (called arguments), which script statements inside the function may examine to extract parameter data.

A function returns execution to the calling statement when the function's last statement has executed. A value may be returned to the calling statement via the return statement. Also, a return statement anywhere else in the function's statements aborts function statement execution at that point and returns control to the calling statement (optionally with a returned value). If one branch of a conditional construction in a function returns a value, each branch, including the main branch, must also return a value, even if that value is null (IE tends to be more forgiving if you don't balance return statements, but it's good programming practice just the same).

Functions have ready access to all global variables that are defined outside of functions anywhere in the document. But variables defined inside a function (the var keyword is required) are accessible only to statements inside the function.

To reference a function object that is defined elsewhere in the document, use the function name without its parentheses. For example, to assign a function to an event handler property, the syntax is:

 objReference.eventHandlerProperty = functionName; 

Starting with Version 4 browsers, you may nest functions inside one another:

 function myFuncA( ) { statements     function myFuncB( ) {        statements     } } 

Nested functions (such as myFuncB) can be invoked only by statements in its next outermost function.

All functions belong to the window in which the function is defined. Therefore, if a script must access a function located in a sibling frame (in the global naming spacenot nested or anonymous functions), the reference must include the frame and the function name:

 parent.otherFrame.someFunction( ) 

See also return and yield among the control structures later in this chapter.


Creating a Function

 function myFunction([param1[, param2[,...paramN]]]) {     statement(s) } var functionRef = function ([param1[, param2[,...paramN]]]) {     statement(s) }; var myFunction = new Function([param1[,...paramN], "statement1[; ... statementN;"])objectRef.methodName = function([param1[, param2 [,...paramN]]]) {     statement(s) }; 


Properties

arguments
arity
caller
constructor
length
prototype

Methods

apply( )
toString( )
call( )
valueOf( )

Returns an arguments object that contains values passed as arguments to the function. Script statements inside the function can access the values through array syntax, which has numeric index values that correspond to incoming parameter values in the order in which they were passed. The content of the arguments array is independent of the parameter variables defined for the function. Therefore, if the function defines two parameter variables but the calling statement passes 10 parameters, the arguments array captures all 10 values in the order in which they were passed. Statements inside the function may then examine the length of the arguments array and extract values as needed. This allows one function to handle an indeterminate number of parameters if the need arises.

For most browsers, you can simply begin the reference to the object with the name of the property (e.g., arguments[2]). But some older browsers require the name of the enclosing function object, as well. All browsers recognize the longer version.


Example

 function myFunc( )     for (var i = 0; i < myFunc.arguments.length; i++) {         ...     } } 


Value

An arguments object.


Returns an integer representing the number of parameters that are defined for the function. This property may be examined in a statement outside of the function, perhaps in preparation of parameters to be passed to the function. Returns the same value as the length property.


Example

 var paramCount = myFunction.arity; 


Value

Integer.


Returns a reference to a function object that contained the statement invoking the current function. This property is readable only by script statements running in function whose caller you wish to reference. Omitted in some pre-1.0 versions of Mozilla, but back in subsequent versions.


Example

 function myFunc( )     if (myFunc.caller == someFuncZ) {         // process when this function is called by someFuncZ     } } 


Value

Function object.


This is a reference to the function that created the instance of a Function objectthe native Function( ) constructor function in browsers.


Example

 if (myVar.constructor == Function) {     // process native function } 


Value

Function object reference.


Returns an integer representing the number of parameters that are defined for the function. This property may be examined in a statement outside of the function, perhaps in preparation of parameters to be passed to the function.


Example

 var paramCount = myFunction.length; 


Value

Integer.


This is a property of the static Function object. Use the prototype property to assign new properties and methods to future instances of functions created in the current document. See the Array.prototype property description for examples.


Example

 Function.prototype.author = "DG"; 


Value

Any data, including function references.


apply([ thisObjectRef[, argumentsArray]])

Invokes the current function, optionally specifying an object to be used as the context for which any this references in the function applies. Parameters to the function (if any) are contained in array that is passed as the second parameter of the apply( ) method. The method can be used with anonymous or named functions. Usage of this method is rare, but provides flexibility that is helpful if your script should encounter a reference to a function and needs to invoke that function, particularly within an object's context.

Consider a script function that is assigned as a method of a custom object:

 // function definition function myFunc(parm1, parm2, parm3) {     // statements } // custom object constructor function customObj(arg1, arg2) {     this.property1 = arg1;     this.property2 = arg2;     this.method1 = myFunc; } var myObjA = new CustomObj(val1, val2); var myObjB = new CustomObj(val3, val4); 

The most common way to execute the myFunc( ) function is as a method of one of the objects:

 myObjA.method1(parmValue); 

But you can invoke the function from a reference to the function, and make the function believe it is being invoked through one of the objects:

 myFunc.apply(myObjB, [parmVal1, parmVal2, parmVal3]); 

If the function (myFunc in this example) has a statement with the this keyword in it, that term becomes a reference to the object context passed as the first parameter to the apply( ) method (myObjB in this example).


Returned Value

None.


Parameters


thisObjectRef

Reference to an object that is to act as the context for the function.


argumentsArray

An array with items that are values to be passed to the function. Array entries are passed to the function in the same order as they are organized in the array.


call([ thisObjectRef[, arg1[, arg2,[... argN]]]])

Invokes the current function, optionally specifying an object to be used as the context for which any this references in the function applies. Parameters to the function (if any) are contained in a comma-delimited list passed as additional parameters to the call( ) method. Other than the way parameters to the function are assembled, the call( ) and apply( ) methods perform the same tasks. See the apply( ) method for more details.


Returned Value

None.


Parameters


thisObjectRef

Reference to an object that is to act as the context for the function.


arg1,...argN

A comma-delimited list of parameters values to be passed to the function.


Returns the object's value (script statement listing and function wrapper) as a string data type. You don't need this method in practice because the browsers automatically convert values to strings when they are needed for display in alert dialogs or in-document rendering.


Returned Value

String.


Parameters

None.


Returns the object's value. When displaying the value, such as in an alert dialog box, the browser converts the value to a string, but the true value is an instance of the Function object.


Returned Value

A function object reference.


Parameters

None.


The Global object lives in every window or frame of a JavaScript-enabled browser (it is created for you automatically). You don't ever reference the object explicitly, but you do reference its properties and methods to accomplish tasks such as converting strings to numbers (via the parseInt( ) or parseFloat( ) methods). Properties act as constants, and thus evaluate to themselves. As an object with global scope, it exposes its members to script statements throughout the page.


Properties

Infinity
NaN
undefined

Methods

atob( )
btoa( )
decodeURI( )
decodeURIComponent( )
encodeURI( )
encodeURIComponent( )
escape( )
eval( )
GetObject( )
isFinite( )
isNaN( )
isXMLName( )
parseInt( )
parseFloat( )
ScriptEngine( )
ScriptEngineBuildVersion( )
ScriptEngineMajorVersion( )
ScriptEngineMinorVersion( )
unescape( )
unwatch( )
watch( )

Provides a numerical positive infinity (or negated with the - operator). We're talking a practical, as opposed to a theoretical, infinity here. Any number smaller than Number.MIN_VALUE or larger than Number.MAX_VALUE is an infinite value in the JavaScript world. How mundane!


Example

 var authorEgo = Infinity; 


Value

Infinity


This is a value that is not-a-number. JavaScript returns this value when a numerical operation yields a non-numerical result because of a flaw in one of the operands. If you want to test whether a value is not a number, use the isNaN( ) global function rather than comparing to this property value. This global property is the value that Number.NaN evaluates to.


Value

NaN


While the undefined data type has been in ECMAScript and browsers since very early times, only recently was it also elevated to a formal property of the Global object. Despite the recent compatibility ratings, you can use its data type (accessed in string form via the typeof operator) comfortably in older browsers.


Value

undefined


atob(" base64EncodedData") btoa(" stringToBeEncoded")

These methods let you convert arbitrary strings (including strings conveying characters representing binary data and Unicode values) to a 65-character subset of the U.S.-ASCII character set. Encoding in this so-called base64 scheme allows any data to be conveyed along even the most rudimentary transport mechanism. You can read about the rationale and internal mechanisms of the encoding/decoding conversions in RFC 1521 of the Internet Engineering Task Force (http://www.ietf.org/rfc/rfc2045.txt).

Use the btoa( ) method to encode string data into the base64 scheme. The resulting encoded data will consist of ASCII characters az, AZ, 09, and three symbols (/, +, =). Use the atob( ) method to decode base64 encoded data back to its original version.


Returned Value

A string.


Parameters


base64EncodedData

A string containing base64 data either encoded on the client or received as part of a document from a server that performs its own encoding.


stringToBeEncoded

A string characters to be encoded to base64 for internal or external use. For example, an encoded value could be assigned to the value property of an input element for submission to a server process designed to receive base64 data.


decodeURI(" encodedURI")

Returns a string with most URI-encoded values in the parameter restored to their original symbols. Operates only on escaped (encoded) characters that are encodable via the encodeURI( ) method.


Returned Value

A string.


Parameters


encodedURI

A string containing a relative or complete encoded URI.


decodeURIComponent(" encodedURIComponent")

Returns a string with all URI-encoded values in the parameter restored to their original symbols. Intended for use on data portions of a URI excluding the protocol. This method replaces the ECMA-deprecated unescape( ) function.


Returned Value

A string.


Parameters


encodedURIComponent

A string containing a relative or complete encoded URI, or portions thereof.


encodeURI(" URIString")

Returns a string with most URI-encodable values in the parameter converted to their escaped versions (e.g., a space character is converted to %20). This method excludes the following characters from conversion:

 ;  /  ?  :  @  &  =  +  $  ,  # 

These characters are valid symbols in URI strings as-is, and should not be converted, and the conversion might invalidate the URI. This method replaces the ECMA-deprecated escape( ) function.


Returned Value

A string.


Parameters


URIString

A string containing a relative or complete plain-text URI.


encodeURIComponent(" URIComponentString")

Returns a string with all characters except Latin character set letters A tHRough Z (upper and lowercases), digits 0 tHRough 9, and a set of URI-friendly symbols (- _ . ! ~ * ( ) ' space) converted to their escaped versions (% symbol followed by the hexadecimal version of their Unicode value). Intended for use on data portions of a URI excluding the protocol.


Returned Value

A string.


Parameters


URIComponentString

A string containing a relative or complete plain-text URI, or portions thereof.


escape(" string"[, 1])

Returns a URL-encoded version of the string passed as a parameter to the function. URL encoding converts most nonalphanumeric characters (except * _ + - . / and, in IE, @) to hexadecimal values (such as %20 for the space character). URL-encoded strings do not normally encode the plus symbol because those symbols are used to separate components of search strings. If you must have the plus symbol encoded as well, Navigator 4 (only) offers a second parameter (a numeral 1) to turn on that switch for the method. Note that this method has been deprecated in favor of the encodeURI( ) and encodeURIComponent( ) methods. This method has been removed from the ECMA 3 specification.


Returned Value

A string.


Parameters


string

Any string value.


eval(" string")

Returns an object reference of the object described as a string in the parameter of the function. For example, if a form has a sequence of text fields named entry1, entry2, entry3, and so on, you can still use a for loop to cycle through all items by name if you let the eval( ) function convert the string representation of the names to object references:

 for (var i = 1; i <=5; i++) {     oneField = eval("document.forms[0].entry" + i);     oneValue = oneField.value;     ... } 

Be aware, however, that the eval( ) method is perhaps the most inefficient and performance-draining method of the entire JavaScript language. There are many other, far more efficient, ways to reference a document tree object when you have only the string ID or name, such as the document.getElementById( ) and, for older browsers, named indexes of the document.forms, document.images, and document.formRef.elements arrays.


Returned Value

Object reference.


Parameters


string

Any string representation of an object reference.


GetObject(" localPathName"[, appName. objectType])

Returns a reference to an ActiveX object hosted on the client machine whose path name the script is aware of. This is an alternate to creating an instance of an ActiveXObject. In addition to specifying the pathname of the control, you can name a data file to open along with the control's application. Append an exclamation point and the name of the file as part of the localPathName parameter. To learn more about invoking ActiveX objects (also called automation objects), visit: http://msdn2.microsoft.com/en-us/library/7tf9xwsc.aspx.


Returned Value

Object reference.


Parameters


localPathName

A string containing a complete pathname (including volume) to the automation object.


appName.objectType

Common syntax to reference a particular application and type of object supported by the automation object whose path is specified in the first parameter.


isFinite( expression)

Returns a Boolean value of TRue if the number passed as a parameter is anything within the range of Number.MIN_VALUE and Number.MAX_VALUE, inclusive. String values passed as parameters cause the function to return false.


Returned Value

Boolean value: TRue | false.


Parameters


expression

Any JavaScript expression.


isNaN( expression)

Returns a Boolean value of true if the expression passed as a parameter does not evaluate to a numeric value. Any expression that evaluates to NaN (such as performing parseInt( ) on a string that does not begin with a numeral) causes the isNaN( ) method to return true.


Returned Value

Boolean value: true | false.


Parameters


expression

Any JavaScript expression.


isXMLName( string)

Returns a Boolean value of true if the string passed as a parameter is a valid local name for XML elements or attributes.


Returned Value

Boolean value: TRue | false.


Parameters


string

Any JavaScript string.


parseInt(" string "[, radix])

Returns an integer value (as a number data type in base-8 or base-10) of the numerals in the string passed as a parameter. The string value must at least begin with a numeral, or the result is NaN. If the string starts with numbers but changes to letters along the way or includes whitespace, only the leading numbers up to the first nonnumeral or whitespace are converted to the integer. Therefore, you can use the expression:

 parseInt(navigator.appVersion) 

to extract only the whole number of the version that leads the otherwise long string that is returned from that property.

The optional radix parameter lets you specify the base of the number being passed to the function. A number string that begins with zero is normally treated as an octal number, which gives you the wrong answer. It is a good idea to use the radix value of 10 on all parseInt( ) functions if all of your dealings are in base-10 numbers.


Returned Value

Integer.


Parameters


string

Any string that begins with one or more numerals, +, or -.


radix

An integer of the number base of the number passed as the string parameter (e.g., 2, 8, 10, 16).


parseFloat( string)

Returns a number value (either an integer or floating-point number) of the numerals in the string passed as a parameter. The string value must at least begin with a numeral, or the result is NaN. If the string starts with numbers but changes to letters along the way, only the leading numbers are converted to the integer. Therefore, you can use the expression:

 parseFloat(navigator.appVersion) 

to extract the complete version number (e.g., 4.03) that leads the otherwise long string that is returned from that property.

If the converted value doesn't have any nonzero values to the right of the decimal, the returned value is an integer. Floating-point values are returned only when the number calls for it.


Returned Value

Number.


Parameters


string

Any string that begins with one or more numerals, +, or -.


These Internet Explorer-only functions reveal information about the scripting engine (JScript, VBScript, or VBA) being used to invoke the method and which version of that engine is installed. For JScript, the version refers to the version of the Jscript.dll file installed among the browser's support files. The major version is the part of the version number to the left of the version decimal point; the minor version is the part to the right of the decimal point. More granular than that is the internal build number that Microsoft uses to keep track of release generations during development and through release.


Returned Value

ScriptEngine( ) returns a string of one of the following engine names: JScript | VBA | VBScript. All other functions return integer values.


Parameters

None.


unescape( string)

Returns a decoded version of the URL-encoded string passed as a parameter to the function. URL encoding converts nonalphanumeric characters (except * _ + - . / and, in IE, @) to hexadecimal values (such as %20 for the space character). Note that this method has been deprecated in favor of the decodeURI( ) and decodeURIComponent( ) methods. This method has been removed from the ECMA 3 specification.


Returned Value

String.


Parameters


string

Any URL-encoded string value.


unwatch( property) watch( property, funcHandler)

These Navigator- and Mozilla-specific functions are used internally primarily by JavaScript debuggers. When a statement invokes the watch( ) function for an object, the parameters include the property whose value is to be watched and the reference to the function to be invoked whenever the value of the property is changed by an assignment statement. To turn off the watch operation, invoke the unwatch( ) function for the particular property engaged earlier.


Returned Value

Nothing.


Parameters


property

The name of the object's property to be watched.


funcHandler

The name of the function (no parentheses) to be invoked whenever the watched property's value changes.


An iterator can act as a read-only property reader of an object, facilitating single-stepping through all properties of an object in the order in which the properties were originally defined. The JavaScript for-in control structure essentially uses the same technique, but by creating a custom iterator object, you control when the next property in the object is read via the next( ) method. Between invocations of the next( ) method, the iterator object instance remembers which item is next in the queue. When the next( ) method finds no further properties to read, it throws a StopIteration exception.

Create a custom interator object by invoking the Iterator( ) constructor function, passing a reference to the object through which you intend to iterate. An optional Boolean second parameter, when set to true, suppresses the property values being returned by the next( ) method.


Creating an Iterator Object

 var myIterator = new Iterator(object[, propertyNameOnlyFlag]); 


Properties

constructor
prototype

Methods

next( )

See the corresponding properties in the Array object description.


next( )

Reads the property of the iterator following the most recent one read. The method returns either an array of the property/value pair or a string of the property name. After the property is read, the iterator keeps the "pointer" in position, awaiting the next invocation of the method. If the method attempts to read a property after the last one, the method throws a StopIteration exception. You can invoke this method in individual steps or within a looping control structure, such as a while construction.


Returned Value

Two-element array when the iterator is created with both property name and value (the default), otherwise a string of just the property name. When the method returns an array, the first element is the property name, the second element is the property value, which may be of any type.


Parameters

None.


The Math object is used only in its static object form as a library of math constant values and (mostly trigonometric) operations. As a result, there is no constructor function. Math object properties are constant values, while methods return a numeric value reflecting some math operation on a value; the original value is not altered when the method is invoked.

Invoking a Math object property or method adheres to the following syntax:

 Math.propertyName Math.method(param1[, param2]) 

Be sure to observe the uppercase "M" in the Math object in script statements. All expressions involving the Math object evaluate to or return a value.


Properties

E
LN10
LN2
LOG10E
LOG2E
PI
SQRT1_2
SQRT2

Methods

abs( )
acos( )
asin( )
atan( )
atan2( )
ceil( )
cos( )
exp( )
floor( )
log( )
max( )
min( )
pow( )
random( )
round( )
sin( )
sqrt( )
tan( )

Returns Euler's constant.


Example

 var num = Math.E; 


Value

2.718281828459045


Returns the natural logarithm of 2.


Example

 var num = Math.LN2; 


Value

0.6931471805599453


Returns the natural logarithm of 10.


Example

 var num = Math.LN10; 


Value

2.302585092994046


Returns the log base-2 of Euler's constant.


Example

 var num = Math.LOG2E; 


Value

1.4426950408889634


Returns the log base-10 of Euler's constant.


Example

 var num = Math.LOG10E; 


Value

0.4342944819032518


Returns the value of π.


Example

 var num = Math.PI; 


Value

3.141592653589793


Returns the square root of 0.5.


Example

 var num = Math.SQRT1_2; 


Value

0.7071067811865476


Returns the square root of 2.


Example

 var num = Math.SQRT2; 


Value

1.4142135623730951


abs( number)

Returns the absolute value of the number passed as a parameter.


Returned Value

Positive number or zero.


Parameters


number

Any number.


acos( number)

Returns the arc cosine (in radians) of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number from -1 to 1.


asin( number)

Returns the arc sine (in radians) of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number from -1 to 1.


atan( number)

Returns the arc tangent (in radians) of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number between negative infinity and infinity.


atan2( x, y)

Returns the angle (in radians) of angle formed by a line to Cartesian point x, y.


Returned Value

Number between -π and π.


Parameters


x

Any number.


y

Any number.


ceil( number)

Returns the next higher integer that is greater than or equal to the number passed as a parameter.


Returned Value

Integer.


Parameters


number

Any number.


cos( number)

Returns the cosine of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number.


exp( number)

Returns the value of Euler's constant to the power of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number.


floor( number)

Returns the next lower integer that is less than or equal to the number passed as a parameter.


Returned Value

Integer.


Parameters


number

Any number.


log( number)

Returns the natural logarithm (base e) of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number.


max( number1, number2)

Returns the greater value of the two parameters.


Returned Value

Number.


Parameters


number1

Any number.


number2

Any number.


min( number1, number2)

Returns the lesser value of the two parameters.


Returned Value

Number.


Parameters


number1

Any number.


number2

Any number.


pow( number1, number2)

Returns the value of the first parameter raised to the power of the second parameter.


Returned Value

Number.


Parameters


number1

Any number.


number2

Any number.


Returns a pseudo-random number between 0 and 1. To calculate a pseudo-random integer between zero and another maximum value, use the formula:

 Math.floor(Math.random( ) * (n+1)) 

where n is the top integer of the acceptable range. To calculate a pseudo-random integer between a range starting with a number other than zero, use the formula:

 Math.floor(Math.random( ) * n - m + 1) + m 

where m is the lowest integer of the acceptable range and n equals the maximum value of the range. Note that the Math.random( ) method does not work in the Windows and Macintosh versions of Navigator 2.


Returned Value

Number from 0 up to, but not including, 1.


Parameters

None.


round( number)

Returns an integer that follows rounding rules. If the value of the passed parameter is greater than or equal to x.5, the returned value is x + 1; otherwise, the returned value is x.


Returned Value

Integer.


Parameters


number

Any number.


sin( number)

Returns the sine (in radians) of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number.


sqrt( number)

Returns the square root of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number.


tan( number)

Returns the tangent (in radians) of the number passed as a parameter.


Returned Value

Number.


Parameters


number

Any number between negative infinity and infinity.


An instance of the Namespace object (from the E4X standard) is an object that typically associates a URI (whose location contains information about the elements defined for the namespace) with a prefix that is prepended to an element's local name. A namespace object instance has two properties, prefix and uri, both of which are string values. Namespace object instances are used as parameter values for some methods of the XML and XMLList objects.

You can create a namespace object by invoking the Namespace( ) constructor function with zero, one, or two parameters. The most common invocation of the constructor is with two parameter strings, the first being the prefix, and the second being the URI, as follows:

 var myNamespace = new Namespace("ns", "http://www.example.com/schema"); 


Creating a Namespace Object

 var myNamespace = new Namespace([prefix],[uri]); 


Properties

constructor
prefix
prototype
uri

Methods

toString( )

See the corresponding properties in the Array object description.


A string containing the namespace prefix. An empty string signifies that the namespace is the default namespace for the XML data.


Example

 var myPrefix = myNamespace.prefix; 


Value

String.


A string containing the namespace URI.


Example

 var myNSUri = myNamespace.uri; 


Value

String.


Returns the object's value as a string data type. For an instance of a Namespace object, the uri property value is returned.


Returned Value

String.


Parameters

None.


A Number object represents any numerical value, whether it is an integer or floating-point number. By and large, you don't have to worry about the Number object because a numerical value automatically becomes a Number object instance whenever you use such a value or assign it to a variable. On the other hand, you might want access to the static properties that only a math major would love.


Creating a Number Object

 var myValue = number; var myValue = new Number(number); 


Properties

constructor
MAX_VALUE
MIN_VALUE
NaN
NEGATIVE_INFINITY
POSITIVE_INFINITY
prototype

Methods

toExponential( )
toFixed( )
toLocaleString( )
toPrecision( )
toString( )
valueOf( )

This is a reference to the function that created the instance of a Number objectthe native Number( ) constructor function in browsers.


Example

 if (myVar.constructor == Number) {     // process native function } 


Value

Function object reference.


Equal to the highest possible number that JavaScript can handle.


Example

 var tiptop = Number.MAX_VALUE; 


Value

1.7976931348623157e+308


Equal to the smallest possible number that JavaScript can handle.


Example

 var itsybitsy = Number.MIN_VALUE; 


Value

5e-324


Equal to a value that is not-a-number. JavaScript returns this value when a numerical operation yields a non-numerical result because of a flaw in one of the operands. If you want to test whether a value is not a number, use the isNaN( ) global function rather than comparing to this property value.


Value

NaN


Values that are outside of the bounds of Number.MIN_VALUE and Number.MAX_VALUE, respectively.


Example

 Number.NEGATIVE_INFINITY 


Value

-Infinity; Infinity


A property of the static Number object. Use the prototype property to assign new properties and methods to future instances of a Number value created in the current document. See the Array.prototype property description for examples. There is little need to create new prototype properties or methods for the Number object.


Example

 Number.prototype.author = "DG"; 


Value

Any data, including function references.


toExponential( fractionDigits)

Returns a string containing the number object's value displayed in JavaScript's exponential notation. The single parameter specifies the number of digits to the right of the decimal to display in the string. For example, if a variable contains the number 9876.54, if you apply the toExponential(10) method, the result is 9.8765400000E+3, with zeroes padding the rightmost digits to reach a total of 10 digits to the right of the decimal. If you specify a parameter that yields a display with fewer digits than in the original number, the returned value is rounded.


Returned Value

String.


Parameters


fractionDigits

An integer specifying the number of digits to the right of the decimal in the returned string.


toFixed( fractionDigits)

Returns a string containing the number object's value displayed with a fixed number of digits to the right of the decimal (useful for currency calculation results). If you specify a parameter that yields a display with fewer significant digits than the original number, the returned value is rounded, but based only on the value of the digit immediately to the right of the last displayed digit (i.e., rounding does not cascade).


Returned Value

String.


Parameters


fractionDigits

An integer specifying the number of digits to the right of the decimal in the returned string.


Returns a string version of the number object's value. The precise format of the returned value is not mandated by the ECMA standard, and may be different from one local currency system to another (as set in the client computer's international preferences). On a U.S. English system, IE 5.5 and later for Windows returns a value with two digits to the right of the decimal (rounding values if necessary), with commas denoting thousands, millions, and so on. IE 5 for Macintosh does the same except for the commas. Mozilla, Safari, and Opera perform no special formatting.


Returned Value

String.


Parameters

None.


toPrecision( precisionDigits)

Returns a string containing the number object's value displayed with a fixed number of digits, counting digits to the left and right of the decimal. If you specify a parameter that yields a display with fewer digits to the left of the decimal than the original number, the returned value is displayed in exponential notation. Truncated values are rounded, but based only on the value of the digit immediately to the right of the last displayed digit (i.e., rounding does not cascade).


Returned Value

String.


Parameters


precisionDigits

An integer specifying the total number of digits in the returned string.


Returns the object's value as a string data type. You don't need this method in practice because the browsers automatically convert Number values to strings when they are needed for display in alert dialogs or in-document rendering.


Returned Value

String.


Parameters

None.


Returns the object's value.


Returned Value

A numeric value.


Parameters

None.


In addition to serving quietly as the foundation of all native JavaScript objects, the Object object is the pure model of the JavaScript objectincluding custom script objects you create. Use the Object object to generate things in your scripts with behaviors that are defined by custom properties and/or methods. Most typically, you start by creating a blank object with the constructor function and then assign values to new properties of that object.

Navigator 4, IE 5 or later, and all modern scriptable browsers also let you assign properties and values via a special literal syntax that also creates the Object instance in the process:

 var myObject = {propName1:propValue1[, propName2:propValue2[, ...propNameN:propValueN]]} 

You can use objects as data structures for structured custom data in your scripts, much like creating an array with named index values.


Creating an Object Object

 var myObject = new Object( ) var myObject = {propName1:propVal1[, propName2:propVal2[,...N]]}; var myObject = new constructorFuncName([propVal1[, propVal2[,...N]]]); 


Properties

constructor
prototype

Methods

hasOwnProperty( )
isPrototypeOf( )
propertyIsEnumerable( )
toLocaleString( )
toString( )
valueOf( )

Provides a reference to the function that created the instance of an Object objectthe native Object( ) constructor function in browsers.


Example

 if (myVar.constructor == Object) {     // process native string } 


Value

Function object reference.


This is a property of the static Object. Use the prototype property to assign new properties and methods to future instances of an Object created in the current document. See the Array.prototype property description for examples.


Example

 Object.prototype.author = "DG"; 


Value

Any data, including function references.


hasOwnProperty(" propertyName")

Returns Boolean true if, at the time the current object's instance was created, its constructor (or literal assignment) contained a property with a name that matches the parameter value. A property assigned to an object via its prototype property is not considered one of the object's own properties.


Returned Value

Boolean value: true | false.


Parameters


propertyName

String containing the name of an object property.


isPrototypeOf( objectReference)

Returns Boolean TRue if the current object and the object passed as a parameter coincide at some point along each object's prototype inheritance chain. Note that different browser implementations do not always agree on the results.


Returned Value

Boolean value: true | false.


Parameters


objectReference

Reference to an object that potentially shares prototype inheritance with the current object.


propertyIsEnumerable(" propertyName")

Returns Boolean true if the property, whose name is passed as a parameter, exposes itself to for-in property inspection through the object.


Returned Value

Boolean value: true | false.


Parameters


propertyName

String containing the name of an object property.


Browsers are free to determine how to localize string representations of object instances. For now, they appear to perform the same action as the toString( ) method, returning the value [object Object].


Returned Value

String.


Parameters

None.


Returns the object's value as a string data type. In recent browsers, this value is [object Object].


Returned Value

String.


Parameters

None.


Returns the object's value.


Returned Value

An object reference.


Parameters

None.


An instance of the QName object (from the E4X standard) is an object that represents a qualified XML name for an element or attribute. A Qname object instance has two properties, localName and uri, both of which are string values. The name( ) method of an XML object returns a value of this object type.

You can create a Qname object by invoking the QName( ) constructor function with zero, one, or two parameters. The most common invocation of the constructor is with two parameters, the first being an instance of a Namespace object (from which the Qname object derives its uri property value), and the second being a string for the local name, as follows:

 var myNamespace = new Namespace("ns", "http://www.example.com/schema"); var myQname = new QName(myNamespace, "widgetNumber"); 


Creating a Namespace Object

 var myQname = new QName([namespaceObject],["localName"]); 


Properties

constructor
localName
prototype
uri

Methods

toString( )

See the corresponding properties in the Array object description.


A string containing the local name portion of a qualified name.


Example

 var myName = myQname.localName; 


Value

String.


A string containing the namespace URI.


Example

 var myNSUri = myQname.uri; 


Value

String.


Returns the object's value as a string data type. For an instance of a QName object, the method returns the uri property value followed by a double colon (the JavaScript/E4X delimiter between a namespace and local name) and the local name.


Returned Value

String in the form: uri::localName.


Parameters

None.


The RegExp object is a static object that both generates instances of a regular expression and monitors all regular expression in the current window or frame. Instances of the RegExp object are covered in the regular expressions object description that follows this section.

Regular expressions assist in locating text that matches patterns of characters or characteristics. For example, a regular expression can be used to find out very quickly if an entry in a text field is a five-digit number. Defining the pattern to match requires knowledge of a separate notation syntax that is beyond the scope of this book (but is covered in Mastering Regular Expressions, by Jeffrey E. F. Friedl, published by O'Reilly). A summary of the syntax can be found in the description of the regular expression object.

In some browsers, properties of the RegExp object store information about the last operation of any regular expression in the document. Therefore, it is conceivable that each property could change after each regular expression operation. Such operations include not only the methods of a regular expression object instance (exec( ) and test( )), but also the String object methods that accept regular expressions as parameters (match( ), replace( ), and split( )). Some of these properties are passed to the regular expression object as well, in preparation for the next operation with the regular expression.

Where supported, all properties have verbose names as well as shortcut names that begin with $.


Properties

index
input
lastIndex
lastMatch
lastParen
leftContext
multiline
prototype
rightContext
$1
$2
$3
$4
$5
$6
$7
$8
$9

This is the zero-based index value of the character position within the string where the most recent search for the pattern began. The lastIndex property provides the end position.


Example

 var srchStart = RegExp.index; 


Value

Integer.


This is the main string against which a regular expression is compared. If the main string is handed to the regular expression operation as a parameter to a method, this value is null. The short version is $_ (dollar sign, underscore). This property is deprecated in JavaScript 1.5.


Example

 RegExp.input = "Four score and seven years ago..."; 


Value

String.


This is the zero-based index value of the character within the string where the next search for the pattern begins. In a new search, the value is zero. You can also set the value manually if you wish to start at a different location or skip some characters. This property is echoed in the regular expression object instance, and is supported there in most browsers.


Example

 myRE.lastIndex = 30; 


Value

Integer.


Returns the string that matches the regular expression as a result of the most recent operation. The short version is $&. This property is deprecated in JavaScript 1.5.


Example

 var matched = RegExp.lastMatch; 


Value

String.


Returns the string that matches the last parenthesized subcomponent of the regular expression as a result of the most recent operation. The short version is $+. This property is deprecated in JavaScript 1.5.


Example

 var myValue = RegExp.lastParen; 


Value

String.


The leftContext property returns the string starting with the beginning of the most recent searched text up to, but not including, the matching string. The rightContext property returns the string starting with the main string portion immediately following the matching string and extending to the end of the string. The short versions are $` and $', respectively. Because the start of subsequent searches on the same main string move inexorably toward the end of the main string, the starting point of the leftContext value can shift with each operation. These properties are deprecated in JavaScript 1.5.


Example

 var wholeContext = RegExp.leftContext + RegExp.lastMatch + RegExp.rightContext; 


Value

String.


Although implemented in NN and Mozilla, this property should be read only from an instance of the RegExp object. See the regular expression object.


See this property for the Array object.


Parenthesized subcomponents of a regular expression return results. These results are stored individually in properties labeled 1 through 9, preceded by the $ shortcut symbol. The order is based on the position of the left parenthesis of a subcomponent: the leftmost subcomponent result is placed into $1. These properties may be used directly within parameters to String methods that use regular expressions (see the String.replace( ) method). These properties are deprecated in JavaScript 1.5.


Example

 RegExp.$2 


Value

String.


A regular expression object is an instance of the RegExp object. Each regular expression object consists of a pattern that is used to locate matches within a string. Patterns for a regular expression can be simple strings or significantly more powerful expressions that use a notation that is essentially a language unto itself. The implementation of regular expressions in JavaScript 1.2 is very similar to the way they are implemented in Perl.

To create a regular expression object, surround the pattern with forward slashes, and assign the whole expression to a variable. For example, the following statement creates a regular expression with a pattern that is a simple word:

 var re = /greet/; 

The re variable can then be used as a parameter in a variety of methods that search for the pattern within some string (you may also use an expression directly as a method parameter, rather than assigning it to a variable).

Regular expression notation also consists of a number of metacharacters that stand in for sometimes complex ideas, such as the boundary on either side of a word, any numeral, or one or more characters. For example, to search for the pattern of characters shown above but only when the pattern is a word (and not part of a word such as greetings), the regular expression notation uses the metacharacters to indicate that the pattern includes word boundaries on both sides of the pattern:

 var re = /\bgreet\b/; 

The following table shows a summary of the regular expression notation used in JavaScript 1.2.

Character

Matches

Example

\b

Word boundary

/\bto/ matches "tomorrow"/to\b/ matches "Soweto"

/\bto\b/ matches "to"

\B

Word nonboundary

/\Bto/ matches "stool" and "Soweto"/to\B/ matches "stool" and "tomorrow"

/\Bto\B/ matches "stool"

\d

Numeral 0 through 9

/\d\d/ matches "42"

\D

Nonnumeral

/\D\D/ matches "to"

\s

Single whitespace

/under\sdog/ matches "under dog"

\S

Single nonwhitespace

/under\Sdog/ matches "under-dog"

\w

Letter, numeral, or underscore

/1\w/ matches "1A"

\W

Not a letter, numeral, or underscore

/1\W/ matches "1%"

.

Any character except a newline

/../ matches "Z3"

[...]

Any one of the character set in brackets

/J[aeiou]y/ matches "Joy"

[^...]

Negated character set

/J[^eiou]y/ matches "Jay"

*

Zero or more times

/\d*/ matches "", "5", or "444"

?

Zero or one time

/\d?/ matches "" or "5"

+

One or more times

/\d+/ matches "5" or "444"

{n}

Exactly n times

/\d{2}/ matches "55"

{n,}

n or more times

/\d{2,}/ matches "555"

{n,m}

At least n, at most m times

/\d{2,4}/ matches "5555"

^

At beginning of a string or line

/^Sally/ matches "Sally says..."

$

At end of a string or line

/Sally.$/ matches "Hi, Sally."


When you create a regular expression, you may optionally wire the expression to work globally (as you probably do if the regular expression is doing a search-and-replace operation with a method, and your goal is a "replace all" result) and to ignore case in its matches. The modifiers that turn on these switches are the letters g and i. They may be used by themselves or together as gi. See also the multiline property for the meaning of the m modifier.

Once you have established a pattern with the regular expression notation, all the action takes place in the regular expression object methods and the String object methods that accept regular expression parameters.


Creating a regular expression Object

 var regExpressionObj = /pattern/ [g | i | m]; var regExpressionObj = new RegExp(["pattern", ["g" | "i" | "m"]]); 


Properties

constructor
global
ignoreCase
lastIndex
multiline
source

Methods

compile( )
exec( )
test( )

See this property for the Array object.


Returns Boolean TRue if the regular expression object instance had the g or i modifiers (respectively) set when it was created. If a regular expression object has both modifiers set (gi), you must still test for each property individually.


Example

 if (myRE.global && myRE.ignoreCase) {     ... } 


Value

Boolean value: TRue | false.


This is the zero-based index value of the character within the string where the next search for the pattern begins. In a new search, the value is zero. You can also set the value manually if you wish to start at a different location or skip some characters.


Example

 myRE.lastIndex = 30; 


Value

Integer.


The value of the regexp's multiline property is determined exclusively by the presence or absence of the "m" flag in the object constructor. In other words, the scripter determines whether the multiline property of the regexp object will be true by explicitly setting the "m" flag, as in:

 var re = /you/gm; 

After the above statement executes, re.multiline is true.

Despite its name, the "m" flag has no bearing on the search for text matches extending across multiple lines of text in a string. All searches work across multiple-line strings anyway. The "m" flag does apply, however, when the regular expression includes the ^ or $ symbols. For example, consider the ^ symbol, which indicates that the pattern must start at the beginning of a string. In the following multiline string:

 Are\n you\n happy? 

the regexp /you/ will find a match because the pattern "you" is someplace within the string. The regexp /^you/ will not find a match because the string does not start with the pattern "you". The regexp /^you/m will find a match because the "m" (multiline) flag says it's OK to treat each physical line of a multiline string as a start of a string.

Be careful when you deploy the "m" flag because not all browsers recognize it. Using the "m" flag causes script errors in the older browsers.


Example

 if (re.multiline) {     ... } 


Value

Boolean.


Returns a string version of the characters used to create the regular expression. The value does not include the forward slash delimiters that surround the expression.


Example

 var myREasString = myRE.source; 


Value

String.


compile(" pattern"[, "g" | "i" | "m"])

Compiles a regular expression pattern into a genuine regular expression object. This method is used primarily to recompile a regular expression with a pattern that may change during the execution of a script.


Returned Value

Reference to a regular expression instance.


Parameters


pattern

Any regular expression pattern as a quoted string. Modifiers for global, ignore case, or both must be supplied as a separate quoted parameter.


exec( string)

Performs a search through the string passed as a parameter for the current regular expression pattern. A typical sequence follows the format:

 var myRE = /somePattern/; var resultArray = myRE.exec("someString"); 

Properties of both the static RegExp and regular expression instance (myRE in the example) objects are updated with information about the results of the search. In addition, the exec( ) method returns an array of data, much of it similar to RegExp object properties. The returned array includes the following properties:


index

Zero-based index of starting character in the string that matches the pattern


input

The original string being searched


[0]

String of the characters matching the pattern


[1]...[n]

Strings of the results of the parenthesized component matches

You can stow away the results of the exec( ) method in a variable, whereas the RegExp property values change with the next regular expression operation. If the regular expression is set for global searching, a subsequent call to myRE.exec("someString") continues the search from the position of the previous match.

If no match is found for a given call to exec( ), it returns null.


Returned Value

An array of match information if successful; null if there is no match.


Parameters


string

The string to be searched.


test( string)

Returns Boolean true if there is a match of the regular expression anywhere in the string passed as a parameter, false if not. No additional information is available about the results of the search. This is the fastest way to find out if a string contains a match for a pattern.


Returned Value

Boolean value: true | false.


Parameters


string

The string to be searched.


A String object represents any sequence of zero or more characters that are to be treated strictly as text (that is, no math operations are to be applied). A large library of methods is divided into two categories. One category surrounds a string with a pair of HTML tags for a variety of HTML character formatting. These methods are used primarily to assist statements that use document.write( ) to dynamically create content, but their functionality is now superceded by style sheets. The second, vital method category is the more traditional set of string parsing and manipulation methods that facilitate finding and copying characters and substrings, case changes, and conversion from string lists to JavaScript arrays.

By and large, you don't have to worry about explicitly creating a string beyond a simple assignment of a quoted string value:

 var myString = "howdy"; 

Occasionally, however, it is helpful to create a string object using the constructor of the static String object. Preparing string values for passage to Java applets often requires this type of string generation:

 var myString = new String("howdy"); 

Other than the constructor, prototype property, and fromCharCode( ) method, all properties and methods are for use with instances of the String object, rather than the static String object.


Creating a String Object

 var myValue = "someString"; var myValue = new String("someString"); 


Properties

constructor
length
prototype

Methods

anchor( )
big( )
blink( )
bold( )
charAt( )
charCodeAt( )
concat( )
fixed( )
fontcolor( )
fontsize( )
fromCharCode( )
indexOf( )
italics( )
lastIndexOf( )
link( )
localeCompare( )
match( )
replace( )
search( )
slice( )
small( )
split( )
strike( )
sub( )
substr( )
substring( )
sup( )
toLocaleLowerCase( )
toLocaleUpperCase( )
toLowerCase( )
toString( )
toUpperCase( )
valueOf( )

This is a reference to the function that created the instance of a String objectthe native String( ) constructor function in browsers.


Example

 if (myVar.constructor == String) {     // process native string } 


Value

Function object reference.


Provides a count of the number of characters in the string. String values dynamically change their lengths if new values are assigned to them or if other strings are concatenated.


Example

 for (var i = 0; i < myString.length; i++) {     ... } 


Value

Integer.


This is a property of the static String object. Use the prototype property to assign new properties and methods to future instances of a String value created in the current document. See the Array.prototype property description for examples.


Example

 String.prototype.author = "DG"; 


Value

Any data, including function references.


anchor(" anchorName")

Returns a copy of the string embedded within an anchor (<a>) tag set. The value passed as a parameter is assigned to the name attribute of the tag.


Returned Value

A string within an a element.


Parameters


anchorName

A string to use as the value of the name attribute.


Returns a copy of the string embedded within a <big> tag set.


Returned Value

A string within a big element.


Parameters

None.


Returns a copy of the string embedded within a <blink> tag set.


Returned Value

A string within a blink element.


Parameters

None.


Returns a copy of the string embedded within a <b> tag set.


Returned Value

A string within a b element.


Parameters

None.


charAt( positionIndex)

Returns a single character string of the character located at the zero-based index position passed as a parameter. Use this method instead of substring( ) when only one character from a known position is needed from a string.


Returned Value

A one-character string. In newer browser versions, an empty string is returned if the parameter value points to a character beyond the length of the string.


Parameters


positionIndex

Zero-based integer.


charCodeAt( positionIndex)

Returns a number of the decimal Unicode value for the character located at the zero-based index position passed as a parameter. For common alphanumeric characters, the Unicode values are the same as ASCII values.


Returned Value

A positive integer. Returns NaN if the parameter value points to a character beyond the length of the string.


Parameters


positionIndex

Zero-based integer.


concat( string2)

Returns a string that appends the parameter string to the current string object. The results of this method are the same as concatenating strings with the add (+) or add-by-value (+=) operators. Neither the method nor operators insert spaces between the two string components.


Returned Value

String.


Parameters


string2

Any string.


Returns a copy of the string embedded within a <tt> tag set.


Returned Value

A string within a tt element.


Parameters

None.


fontColor( color)

Returns a copy of the string embedded within a font (<font>) tag set. The value passed as a parameter is assigned to the color attribute of the tag.


Returned Value

A string within a font element.


Parameters


color

A string to use as the value of the color attribute.


fontSize( size)

Returns a copy of the string embedded within a font (<font>) tag set. The value passed as a parameter is assigned to the size attribute of the tag.


Returned Value

A string within a font element.


Parameters


size

An integer to use as the value of the size attribute.


String.fromCharCode( num1, [, num2,[... numN]])

This is a static method that returns a string of one or more characters with Unicode values that are passed as a comma-delimited list of parameters. For example, the expression:

 String.fromCharCode(120, 121, 122) 

returns "xyz".


Returned Value

A string.


Parameters


num1...numN

One or more integer values in an unquoted, comma-delimited list.


indexOf( searchString[, startPositionIndex])

Returns a zero-based integer of the position within the current string where the searchString parameter starts. Normally, the search starts with the first (index of zero) character, but you may have the search begin later in the string by specifying the optional second parameter, which is the index value of where the search should start. If there is no match, the returned value is -1. This is a backward-compatible quick way to find out if one string contains another: if the returned value is -1 then you know the searchString is not in the larger string. If the returned value is another number (the precise value doesn't matter), the searchString is in the larger string. For browsers that support regular expressions, the String object's search( ) method performs a similar function.


Returned Value

Integer.


Parameters


searchString

A string to look for in the current string object.


startPositionIndex

A zero-based integer indicating the position within the current string object to begin the search of the first parameter.


Returns a copy of the string embedded within an <i> tag set.


Returned Value

A string within an i element.


Parameters

None.


lastIndexOf( searchString[, startPositionIndex])

Returns a zero-based integer of the position within the current string object where the searchString parameter starts. This method works like the indexOf( ) method but begins all searches from the end of the string or some index position. Even though searching starts from the end of the string, the startPositionIndex parameter is based on the start of the string, as is the returned value. If there is no match, the returned value is -1.


Returned Value

Integer.


Parameters


searchString

A string to look for in the current string object.


startPositionIndex

A zero-based integer indicating the position within the current string object to begin the search of the first parameter. Even though the search starts from the end of the string, this parameter value is relative to the front of the string.


link( URL)

Returns a copy of the string embedded within an anchor (<a>) tag set. The value passed as a parameter is assigned to the href attribute of the tag.


Returned Value

A string within an a element.


Parameters


URL

A string to use as the value of the href attribute.


localeCompare( string2)

Returns a number indicating whether the current string sorts before, the same as, or after the parameter string, based on browser- and system-dependent string localization. If the current string sorts before the parameter string, the return value is a negative number; if they are the same, the return value is 0, if the current string sorts after the parameter string, the return value is a positive number.

Use this method with caution if the strings contain characters outside the Latin character set because each browser can determine what localization equalities are in place. They also calculate the return values differently.


Returned Value

Integer


Parameters


string2

Any string.


match( regexpression)

When you create the regular expression with the "g" flag, returns an array of strings within the current string that match the regular expression passed as a parameter. For example, if you pass a regular expression that specifies any five-digit number, the returned value of the match( ) method would be an array of all five-digit numbers (as strings) in the main string. Properties of the RegExp static object are influenced by this method's operation.

When the regular expression is defined without the "g" flag, the method returns an array object whose zero index location is the first matched string, and whose two properties are index (a pointer to the zero-based string character position where the match begins) and input (a copy of the string).


Returned Value

An array of strings.


Parameters


regexpression

A regular expression object. See the regular expression object for the syntax to create a regular expression object.


replace( regexpression, replaceString)

Returns the new string that results when matches of the regexpression parameter are replaced by the replaceString parameter. The original string is unharmed in the process, so you need to capture the returned value in a variable to preserve the changes.


Returned Value

A string.


Parameters


regexpression

A regular expression object. If you want the replace( ) method to act globally on the string, set the global switch (g) on the regular expression. See the regular expression object for the syntax to create a regular expression object.


replaceString

A string that is to take the place of all matches of regexpression in the current string.


search( regexpression)

Returns the zero-based indexed value of the first character in the current string that matches the pattern of the regexpression parameter. This method is similar to the indexOf( ) method, but the search is performed with a regular expression rather than a straight string.


Returned Value

Integer.


Parameters


regexpression

A regular expression object. See the regular expression object for the syntax to create a regular expression object.


slice( startPositionIndex, endPositionIndex])

Returns a substring of the current string. The substring is copied from the main string starting at the zero-based index count value of the character in the main string. If no second parameter is provided, the substring extends to the end of the main string. The optional second parameter can be another zero-based index value of where the substring should end. This value may also be a negative value, which counts from the end of the string toward the front.


Returned Value

String.


Parameters


startPositionIndex

A zero-based integer indicating the position within the current string object to start copying characters.


endPositionIndex

A zero-based integer indicating the position within the current string object to end copying characters. Negative values count inward from the end of the string.


Returns a copy of the string embedded within a <small> tag set.


Returned Value

A string within a small element.


Parameters

None.


split( delimiter [, limitInteger])

Returns a new array object whose elements are segments of the current string. The current string is divided into array entries at each instance of the delimiter string specified as the first parameter of the method. The delimiter does not become part of the array. You do not have to declare the array prior to stuffing the results of the split( ) method. For example, if a string consists of a comma-delimited list of names, you can convert the list into an array as follows:

 var listArray = stringList.split(","); 

You may also use a regular expression as the parameter to divide the string by a pattern rather than a fixed character.


Returned Value

Array.


Parameters


delimiter

A string or regular expression that defines where the main string is divided into elements of the resulting array.


limitInteger

An optional integer that restricts the number of items converted into array elements.


Returns a copy of the string embedded within a <strike> tag set.


Returned Value

A string within a strike element.


Parameters

None.


Returns a copy of the string embedded within a <sub> tag set.


Returned Value

A string within a sub element.


Parameters

None.


substr( startPositionIndex [, length])

Returns a copy of an extract from the current string. The extract begins at the zero-based index position of the current string as specified by the first parameter of the method. If no other parameter is provided, the extract continues to the end of the main string. The second parameter can specify an integer of the number of characters to be extracted from the main string. In contrast, the substring( ) method's parameters point to the start and end position index values of the main string.


Returned Value

A string.


Parameters


startPositionIndex

A zero-based integer indicating the position within the current string object to start copying characters


length

An optional integer of the number of characters to extract, starting with the character indicated by the startPositionIndex parameter


substring( startPositionIndex, endPositionIndex)

Returns a copy of an extract from the current string. The extract begins at the zero-based index position of the current string as specified by the first parameter of the method and ends just before the character whose index is specified by the second parameter. For example, "Frobnitz".substring(0,4) returns the substring from positions 0 through 3: Frob. In contrast, the substr( ) method's parameters point to the start position of the main string and the number of characters (length) to extract.


Returned Value

A string.


Parameters


startPositionIndex

A zero-based integer indicating the position within the current string object to start copying characters.


endPositionIndex

A zero-based integer indicating the position within the current string object to end copying characters. In other words, the copy is made from startPositionIndex up to, but not including, the character at position endPositionIndex.


Returns a copy of the string embedded within a <sup> tag set.


Returned Value

A string within a sup element.


Parameters

None.


Return a copy of the current string in all lowercase or uppercase letters. Works the same as the regular version, except for some non-Latin alphabets with character mappings that may require special internal handling.


Returned Value

String.


Parameters

None.


Return a copy of the current string in all lowercase or uppercase letters. If you want to replace the current string with a case-adjusted version, assign the result of the method to the same string:

 myString = myString.toUpperCase( ); 

It is common to use either one of these methods to create a case-insensitive comparison of two strings. This is especially convenient if one of the strings being compared is entered by a user, who may submit a variety of case situations:

 if (document.forms[0].entry.value.toLowerCase( ) == compareValue) {     ... } 


Returned Value

String.


Parameters

None.


Return a string value of the object.


Returned Value

String value.


Parameters

None.


The VBArray object lets JavaScript communicate with Visual Basic safe arrays. This kind of array is read-only, can be multidimensional, and is sometimes returned as a value from ActiveX controls. Methods of this object give JavaScript access to the VBArray data. For additional details, visit http://msdn2.microsoft.com/en-us/library/3s0fw3t2.aspx.


Creating a VBArray

 var myVBA = new VBArray(externalArray); 


Properties

None.


Methods

dimensions( )
getItem( )
lbound( )
toArray( )
ubound( )

Returns an integer corresponding to the number of dimensions of the VBArray.


Returned Value

Integer.


Parameters

None.


getItem( dim1[, dim2[, ...dimN]])

Returns the value of an item from the VBArray. Parameters specify the location in the array.


Returned Value

Number, string, or other value from the VBArray.


Parameters


dimN

Integer for the location within the array. For a multiple-dimension VBArray, use a comma-delimited map to the position.


lbound( dim) ubound( dim)

Return an integer of the lowest and highest index values available for a particular dimension of a VBArray.


Returned Value

Integer


Parameters


dim

Integer for the location within the array.


Returns a JavaScript array version of the VBArray.


Returned Value

Array.


Parameters

None.


An instance of the XML object (from the E4X standard) is a container of XML data. Such data can range from an empty text node to a complex XML element, such as one representing a SOAP query or a container of multiple "record" elements returned from a database query.

You have two primary ways to create an XML object. The first is via the traditional object constructor function call, as in:

 var myXml = new XML( ); 

When you don't pass any value as a parameter, the constructor returns an empty text node. But you may also pass a string representing any component of an XML document, from a text node value to nested XML elements, as in:

 var myXml = new XML("<season><bowl><number>I</number><year>1967</year><winner> Packers</winner><loser>Chiefs</loser></bowl></season>"); 

Once you have an instance of an XML object, you can then use familiar JavaScript property notation to obtain the value of an element. Given that the instance evaluates to the root node of the data, use "dot" syntax to traverse the hierarchy:

 var bowlYear = myXml.bowl.year; 

Even this "extract" from myXml is, itself, an instance of the XML object, and has full use of instance methods, but from the narrower scope of, in this case, the year element only.

When a scripted reference points to an element that is repeated at the same level in the XML data, the expression evaluates to an XMLList object containing all instances of like-named elements at that level as XML objects. For example, if the Super Bowl data had multiple bowl elements for several years (see the XML file described in Online Section IV, as it is used for several examples here), the following expression yields an XML list of all of those bowl elements:

 var allBowls = myXml.bowl; 

Therefore, when you drill down one level further, to the following:

 var allYears = myXml.bowl.year; 

the expression evaluates to another XMLList object containing all year elements spread across all bowl elements.

E4X provides a notation shortcut when a reference needs to traverse multiple containment levels. The descendant accessor (..) searches the XML object on the left side for all instances of elements whose names match the right side, regardless of how deeply they're nested. For example, to obtain references to all of the year elements, the descendant accessor syntax is as follows:

 var allYears = myXml..year; 

When you have multiple elements of the same name, you can also target an individual element or like elements if you know one of its subelements and values. For example, consider an XML object containing multiple bowl elements (like the XML data described in Online Section IV). To extract a collection of bowl elements in which the value of the winner element is "Packers," the syntax would be as follows:

 var thePack = myXml.bowl.(winner=="Packers"); 

The result is a collection of XML objects (XMLList) of zero or more bowl elements meeting the stated criterion.

Use the standard JavaScript assignment operator (=) to plug a new value into the text node of an element:

 myXml.bowl.number = "II"; myXml.bowl.year = 1968; 

Similarly, you can add elements, attributes, and values to XML data via assignment operators. For example, to add a winscore element and value to the bowl element of the XML object created above, use the following statement:

 myXml.bowl.winscore = 35; 

The resulting XML (pretty printed) is as follows:

 <season>   <bowl>     <number>I</number>     <year>1967</year>     <winner>Packers</winner>     <loser>Chiefs</loser>     <winscore>35</winscore>   </bowl>   ... </season> 

To reference an attribute of an element, use the @ prefix. For example, to add an attribute to the number element above, use the following statement:

 myXml.bowl.number.@type = "Roman Numeral"; 

The resulting element becomes:

 <number type="Roman Numeral">I</number> 

Just as arrays and objects have literals to assist in their creation ([ ] and { }, respectively), so, too, do XML objects. The left angle bracket of a tag signals the beginning of an XML object literal, which ends with the corresponding end tag. Note that there are no quotes surrounding the value, but quotes would be embedded within the right side expression to surround attribute values. For example,

 var myXml = <season>   <bowl>     <number type="Roman Numeral">I</number>     <year>1967</year>     <winner>Packers</winner>     <loser>Chiefs</loser>   </bowl> </season>; 

This is the notation that causes the most backward compatibility problems if a browser fails to recognize the text/javascript; e4x=1 type as being different from the regular text/javascript type. Such a browser will interpret the left angle bracket as an operator located in an illegal position.

To place a JavaScript-computed value inside an XML objectperhaps a variable containing an accumulated string or a calculated number resultsurround the expression with curly braces, as follows:

 // a sample global object with some properties/values var teams = {_1967: {winner:"Packers", loser:"Chiefs"}, _1968: {...}, ...}; // use object properties as element values var myXml = <season>   <bowl>     <number>I</number>     <year>1967</year>     <winner>{teams._1967.winner}</winner>     <loser>{teams._1967.loser}</loser>   </bowl> </season>; 

You can create an empty element and populate it with additional child nodes using JavaScript syntax, as follows:

 var bowlXML = <bowl/>; bowlXML.number = "I"; bowlXML.number.@type = "Roman Numeral"; bowlXML.year = 1967; ... 

While the JavaScript object/property assignment technique works well, you also have a wide range of methods of an XML object that give you more control over the contents of an existing XML object, including inserting and remove elements at specific locations.

To convert an instance of an XML object to a string for posting to a server, use the toString( ) method.

All properties and the defaultSettings( ), setSettings( ), and settings( ) methods described below are members of the static XML object. All other methods are used with instances.


Creating an XML Object

 var myXml = new XML([XMLString]); var myXml = XMLMarkup; 


Properties

constructor
ignoreComments
ignoreProcessingInstructions
ignoreWhitespace
prettyIndent
prettyPrinting
prototype

Methods

addNamespace( )
appendChild( )
attribute( )
attributes( )
child( )
childIndex( )
children( )
comments( )
contains( )
copy( )
defaultSettings( )
descendants( )
elements( )
hasComplexContent( )
hasOwnProperty( )
hasSimpleContent( )
inScopeNamespaces( )
insertChildAfter( )
insertChildBefore( )
length( )
localName( )
name( )
namespace( )
namespaceDeclarations( )
nodeKind( )
normalize( )
parent( )
prependChild( )
processingInstructions( )
propertyIsEnumerable( )
removeNamespace( )
replace( )
setChildren( )
setLocalName( )
setName( )
setNamespace( )
setSettings( )
settings( )
text( )
toString( )
toXMLString( )
valueOf( )

See the corresponding properties in the Array object description.


Instructs the constructor not to create comment nodes, even if comments are included in the source material. The default value is true, so you must explicitly turn on comments if you wish them to be included in the XML code.


Example

 XML.ignoreComments = false; 


Value

Boolean.


Instructs the constructor not to create processing instruction nodes, even if they are included in the source material. The default value is true, so you must explicitly turn on processing instructions if you wish them to be included in the XML code.


Example

 XML.ignoreProcessingInstructions = false; 


Value

Boolean.


Instructs the constructor to discard insignificant whitespace characters (space, carriage return, line feed, tab), even if they are included in the source material. The default value is TRue, so you must explicitly turn on whitespace if you wish source code whitespace to be included in the XML code.


Example

 XML.ignoreWhitespace = false; 


Value

Boolean.


Controls the number of spaces the browser uses to indent elements when an XML object is converted to a string and the XML.prettyPrinting property is turned on (which it is by default). The default value is 2.


Example

 XML.prettyIndent = 3; 


Value

Positive integer or zero.


Controls whether string conversions of an XML object (via toString( ) or toXMLString( )) formats the output with whitespace (carriage returns, indentation, etc.) or as a contiguous string. The amount of indentation is controlled by the XML.prettyIndent property. The default behavior is for pretty printing to be on (true) and indentation of two spaces per level.


Example

 XML.prettyPrinting = false; 


Value

Boolean.


addNamespace( namespaceObject)

Inserts a namespace declaration into the root node of an XML object. See the Namespace object for constructor information.


Applies To

XML


Returned Value

Reference to the modified XML object instance.


Example

 myXml.addNamespace(new Namespace("ex", "http://www.example.com/ns")); 


Parameters


namespaceObject

Reference to a namespace object instance.


appendChild( childXMLObject)

Inserts an XML object (typically an element or text node) at the end of all other children (if any) of the root node invoking the method.


Applies To

XML


Returned Value

Reference to the modified XML object instance.


Example

 myXml.bowl.(year == 1995)[0].appendChild(<stadium>Joe Robbie Stadium</stadium>); 


Parameters


childXMLObject

Reference to an XML object instance.


attribute(" attributeName")

Returns an XMLList object whose items evaluate to values of XML objects that have an attribute matching the value passed as a parameter.


Applies To

XML, XMLList


Returned Value

Xmllist object of zero or more XML objects.


Example

 var typeList = myXml.bowl.number.attribute("type"); 


Parameters


attributeName

String value of the name of the attribute to look for within the current XML object.


Returns an XMLList object whose items evaluate to values of all attributes defined for the current XML object.


Applies To

XML, XMLList


Returned Value

Xmllist object of zero or more matching XML objects.


Example

 var valueList = myXml.bowl.number.attributes( ); 


Parameters

None.


child(" propertyName")

Returns an XMLList object whose items evaluate to values of XML objects that are children of the current object(s) and whose element names match the value passed as a parameter. If you were distributing values from XML records down an HTML table column, this method lets you obtain all values for that column via this method.


Applies To

XML, XMLList


Returned Value

Xmllist object of zero or more XML objects.


Example

 var yearsList = myXml.bowl.child("year"); 


Parameters


propertyName

String value of the name of the child elements to look for within the current XML object.


Returns a zero-based integer indicating the child position of the current XML object within its parent element.


Applies To

XML


Returned Value

Positive integer or 0.


Example

 var where = myXml.employee.(id == "2f4"); 


Parameters

None.


Returns an XMLList object containing references to all child elements of the current XML object. The XMLList object has only as many items as there are immediate children of the current object. But because each item in the list is a reference to an XML object, that object's nested children are also accessible through further inspection.


Applies To

XML, XMLList


Returned Value

Xmllist object.


Example

 var kids = myXml.children( ); 


Parameters

None.


Returns an XMLList object containing references to all comment elements among the immediate children of the current object. If scripts are used to create the XML object instance, the XML.ignoreComments property must be set to false for the comments to become part of the XML object.


Applies To

XML, XMLList


Returned Value

Xmllist object.


Example

 var topLevelComments = myXml.comments( ); 


Parameters

None.


contains(" value")

Returns TRue if the value of the current XML object (or objects for an XMLList) matches the value passed as a parameter.


Applies To

XML, XMLList


Returned Value

Boolean.


Example

 if (myXml.bowl.winner.contains("Packers")) {...}; 


Parameters


value

String value to compare against the current XML object's value (or values for an XMLList).


Returns a copy of the current XML or XMLList object. All nested elements are included in the copy.


Applies To

XML, XMLList


Returned Value

Xml or XMLList object, depending on type of current object.


Example

 var oneCopy = myXml.copy( ); 


Parameters

None.


XML.defaultSettings( )

Returns a JavaScript object whose properties are the entire set of global properties for the static XML object (ignoreComments, ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and prettyPrinting) and their default values. Use the result of this method as a parameter for setSettings( ) to restore all values to their default settings in one statement.


Returned Value

JavaScript object.


Example

 XML.setSettings(XML.defaultSettings( )); 


Parameters

None.


descendants([" elementName"])

Returns an XMLList object containing XML objects for all descedants of the current object(s) (when no parameter is passed) or only those descendants whose element name matches the passed parameter. The reach of the descendants( ) method includes nested descendants, as well. Each descendant becomes a first-class item in the list, meaning that for a complex set of XML data, the list could be very large.


Applies To

XML, XMLList


Returned Value

Xmllist.


Example

 var allDescendants = myXml.descendants( ); 


Parameters


elementName

String value to compare against the names of all elements nested in the current object(s).


elements(" name")

Returns an XMLList object whose items evaluate to values of XML objects that are children of the current object(s) (with no parameter) and whose element names match the value passed as a parameter. Only element objects are added to the list, omitting comments and processing instructions (in case they're in the XML data).


Applies To

XML, XMLList


Returned Value

Xmllist object of zero or more XML objects.


Example

 var yearsList = myXml.bowl.elements("year"); 


Parameters


name

String value of the name of the child elements to look for within the current XML object.


Returns true if the current XML object contains an element that has child elements, and is thus said to have complex content.


Applies To

XML, XMLList


Returned Value

Boolean.


Example

 if (myXml.employee[3].hasComplexContent( )) {    // statements }; 


Parameters

None.


hasOwnProperty(" propertyName")

Returns TRue if the current XML object contains an element whose name matches the string passed as a parameter. The method also works on the static XML object, in which case you can test for the presence of properties and methods (e.g., XML.hasOwnProperty("addNamespace")).


Applies To

XML, XMLList


Returned Value

Boolean.


Example

 if (myXml.hasOwnProperty("age")) {    // statements }; 


Parameters


propertyName

String value of the name of elements to look for within the current XML object, or properties/methods of the static XML object.


Returns true if the current XML object contains an element that has no child elements or is a text or attribute node. Note that an element that has a text node for its value and no other child elements is considered simple content.


Applies To

XML, XMLList


Returned Value

Boolean.


Example

 if (myXml.employee[3].age.hasSimpleContent( )) {    // statements }; 


Parameters

None.


Returns an array of Namespace objects within the scope of the current XML object's parent. If no namespaces have been explicitly declared, the result is an empty array.


Applies To

XML


Returned Value

Array.


Example

 var nsList = myXml.inScopeNamespaces( ); 


Parameters

None.


insertChildAfter( referenceChild, newChild)


insertChildBefore( referenceChild, newChild)

Inserts a new child element (second parameter) after or before a referenced child (first parameter) of the current XML object, returning a reference to the newly updated XML object. If you pass null as a first parameter, insertChildAfter( ) inserts the new child as the first child (i.e., after none of the child elements), while insertChildBefore( ) inserts the new child as the last child (i.e., before none of the child elements). The current object is modified, as well as returning a reference to the modified object.


Applies To

XML


Returned Value

XML object.


Example

 myXml.bowl[0].insertChildBefore(myXml.bowl[0].winner[0], <stadium>Lambeau Field</ stadium>); 


Parameters


referenceChild

A reference to the child of the current object to be used as a reference point for insertion; also null, which short-circuits the reference point to mean "after" or "before" none of the existing children.


newChild

An XML object to be inserted.


Returns an integer count of the number of objects contained by the instance of an XML or XMLList object. The value is always 1 for an XML object, and the actual count for an XMLlist object.


Applies To

XML, XMLList


Returned Value

Integer.


Example

 var howMany = myXml.bowl.length( ); 


Parameters

None.


Returns a string of the local name part of an XML object's qualified name. For an element whose names do not have a namespace prefix, the localName( ) and name( ) methods return the same value.


Applies To

XML


Returned Value

String.


Example

 var myXml = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var elemLocName = myX.children( )[0].localName( );     // result is "title" 


Parameters

None.


Returns a string of the fully qualified name part of an XML object. For an element whose names do not have a namespace prefix, the localName( ) and name( ) methods return the same value.


Applies To

XML


Returned Value

String.


Example

 var myXml = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var elemLocName = myX.children( )[0].localName( );     // result is "title" 


Parameters

None.


namespace([ "prefix"])

Returns a namespace object whose properties convey the prefix and URI specified for the namespace for the current XML object. You can optionally specify a prefix as a parameter so that the method returns a value only for a matching prefix. If the prefix does not match, the method returns undefined.


Applies To

XML


Returned Value

Namespace object.


Example

 var myXml = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var elemLocName = myX.children( )[0].namespace("libBook");     // result is a Namespace object 


Parameters


prefix

A string of a qualified name prefix (without a colon).


Returns an array of namespace objects. Each entry is a namespace that is associated with the current XML object, including those defined in its parent.


Applies To

XML


Returned Value

Array.


Parameters

None.


Returns a string that identifies the type of DOM node that the current XML object represents.


Applies To

XML


Returned Value

One of the following string values: element, attribute, comment, processing-instruction, text.


Parameters

None.


Just like the DOM method of the same name, this version unites adjacent text nodes in the current element or XMLList into a single text node. Text nodes inserted into an element (e. g., via the prependChild( ) method) are maintained as separate nodes (when pretty printed, each text node of an element appears on its own line).


Applies To

XML, XMLList


Returned Value

An XML or XMLList value (depending on the type of object invoking the method) with the normalized content.


Parameters

None.


Returns a reference to the parent element of the current XML or XMLList object.


Applies To

XML, XMLList


Returned Value

An XML or XMLList value (depending on the type of object invoking the method) with the normalized content. If the object has no parent, the method returns an empty object. If the current object is a list of elements that have multiple parents, the method returns undefined.


Example

 var parentElem = myXml.bowl.parent( ); 


Parameters

None.


prependChild( newChild)

Inserts an XML object as the first child of the current XML object, returning a reference to the current object after the insertion. The original object is also modified.


Applies To

XML


Returned Value

XML object.


Example

 var txt = new XML("Super Bowl "); myXml.bowl[20].number[0].prependChild(txt); 


Parameters


newChild

An instance of an XML object.


processingInstructions([ "name"])

Without a parameter, returns an XMLList of all processing instruction nodes contained by the current XML object. You may optionally pass a name as a parameter, in which case the


method returns an XMLList with all processing instruction nodes that have the matching name.


Applies To

XML, XMLList


Returned Value

Xmllist object.


Parameters


name

A string of a processing instruction node's name.


Eventually, this method should let a script control whether an element in an XML object is exposed to inspection routines, such as for-in constructions. For the first publication of E4X, however, the method is not connected to a meaningful operation.


Applies To

XML, XMLList


Returned Value

Boolean.


removeNamespace( namespaceObject)

Deletes a namespace declaration from the current XML object. Note, however, that child elements that use the deleted namespace's prefix in element and attribute names continue to have the prefix attached to those items. The method returns a reference to the modified XML object.


Applies To

XML


Returned Value

XML object.


Example

 var myX = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var ns = new Namespace("libBook","http://catalog.example.edu/schema"); myX.removeNamespace(ns); // returned value (toXMLString( )) is: //    <results> //      <libBook:title libBook:rarebooks="true">De Principia</libBook:title> //    </results> 


Parameters


namespaceObject

An instance of an Namespace object.


replace( elementNameStringOrNumber, newValue)

Replaces one or more child elements of the current object with a different XML object, including an instance of XML (any node type) or XMLList. The first parameter must reference a child element or group of identically named elements by a string or a zero-based integer signifying the index position of the element to be replaced. When the element you intend to replace is, itself, a parent of other elements, all descendants are removed in the operation. When you specify a string element name, if there are multiple elements with the same name, they are all replaced with a single instance of the value of the second parameter. If an element containing a value is replaced by an empty element, the original value is lost in the process (although for a single element, you can construct a script that grabs the value prior to replacement and uses curly braces to script the value of the new element before it is placed in position). The method returns a reference to the modified XML object.


Applies To

XML


Returned Value

XML object.


Example

 // replace all track elements with one empty track myXml.mix.replace("track", <track/>); // replace all year elements with anno elements, preserving values for each (var elem in myXml.bowl) {     elem.replace("year", <anno>{elem.year.toString( )}</anno>); } 


Parameters


elementNameStringOrNumber

Either a string of a child element name or a zero-based integer index to the desired child element of the current XML object.


newValue

An instance of an XML or XMLList object, including a text node.


setChildren( newValue)

Replaces all child elements of the current object (and their descendants) with a different XML object, including an instance of XML (any node type) or XMLList. The method returns a reference to the modified XML object.


Applies To

XML


Returned Value

XML object.


Example

 // massive layoff myXml.employees.setChildren(<vacancy/>); 


Parameters


newValue

An instance of an XML or XMLList object, including a text node.


setLocalName(" newName")

Replaces the local name portion of the current XML object with a new value. The prefix is undisturbed.


Applies To

XML


Returned Value

None.


Example

 var myX = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var ns = new Namespace("libBook","http://catalog.example.edu/schema"); myX.ns::title.setLocalName("bookTitle"); // element becomes: //    <libBook:bookTitle libBook:rarebooks="true">De Principia</libBook:bookTitle> 


Parameters


newName

A string value of the new element local name portion.


setName(" newName")

Replaces the name of the current XML object with a new value. If the element's original name has a namespace prefix, the prefix is also removed.


Applies To

XML


Returned Value

None.


Example

 var myX = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var ns = new Namespace("libBook","http://catalog.example.edu/schema"); myX.ns::title.setName("bookTitle"); // element becomes: //    <bookTitle libBook:rarebooks="true">De Principia</bookTitle> 


Parameters


newName

A string value of the new element local name portion.


setNamespace( namespaceObject)

Replaces the namespace of the current XML object (element or attribute type) with a new value. To assign a namespace to an element or attribute that doesn't already have a namespace declaration, use addNamespace( ).


Applies To

XML


Returned Value

None.


Example

 var myX = <results xmlns:libBook="http://catalog.example.edu/schema">     <libBook:title libBook:rarebooks="true">De Principia</libBook:title></results>; var ns = new Namespace("libBook","http://catalog.example.edu/schema"); var updatedNS = new Namespace("dg", "http://www.dannyg.com/ns"); myX.ns::title.setNamespace(updatedNS); // element becomes: //    <results> //      <dg:title xmlns:dg="http://www.dannyg.com/ns" libBook:rarebooks= "true">De Principia</libBook:title> //    </results> 


Parameters


namespaceObject

An instance of the Namespace object.


XML.setSettings([ settingsObject])

Controls the global properties of the static XML object in one statement. Passing no parameter, null, or undefined causes all settings to revert to their default values. Otherwise pass an object whose five property names are the names of the five global properties (ignoreComments, ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and prettyPrinting).


Returned Value

None


Parameters


settingsObject

An optional JavaScript object whose five properties and values are structured as follows:

 {ignoreComments: Boolean, ignoreProcessingInstructions: Boolean, ignoreWhitespace: Boolean, prettyPrinting: Boolean, prettyIndent: Integer} 


XML.settings( )

Returns a JavaScript object whose properties are the entire set of global properties for the static XML object (ignoreComments, ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and prettyPrinting) and their values. You can use this to preserve a set of custom settings before temporarily changing one or more other properties. Then use the saved value as a parameter to setSettings( ) to restore all values to their previous settings in one statement.


Returned Value

JavaScript object.


Parameters

None.


Returns an XMLList of all child text nodes of the current XML object. If the current XML object represents a single element, the returned XMLList has a single item in it, the text node as an XML object. You can obtain the text nodes of all like children by supplying an XMLList of elements that have child text nodes. For example, in the Super Bowl XML data from Online Section IV, there are a series of bowl elements, each of which contains a year element that has a text node. To obtain an XMLList of all of the year element text nodes in the data, the expression would be:

 myXml.bowl.year.text( ) 

You can usually rely on implicit type conversion on each element of the XMLList to obtain the string value for further script manipulation of those values outside of the XML data. If you encounter difficulty, use the toString( ) method on individual items to obtain string values.


Applies To

XML, XMLList


Returned Value

Xmllist object.


Parameters

None.


Returns a string value type of text node or attribute node portions (simple content) of an element represented as an XML object. For an instance of a single XML object or an XMLList object containing only one item, the returned string is generally usable data. If the current object is a multi-item XMLList, all of the values are scrunched together with no delimiters between element values.

In most cases, you won't need to invoke toString( ) because JavaScript performs implicit type conversion when an expression calls for a string value and you supply an XML object.


Applies To

XML, XMLList


Returned Value

String value.


Parameters

None.


Returns a string value type of the current XML object, complete with tags, attributes, and namespace declarationsa source code view, if you will, of the data. This method applies to both simple XML objects and xmllists. Global values for pretty printing are applied to the output generated by toXMLString( ).


Applies To

XML, XMLList


Returned Value

String value.


Parameters

None.


Returns a reference to the current XML object.


Applies To

XML, XMLList


Returned Value

XML object


Parameters

None.


An instance of the XMLList object (from the E4X standard) is a container of zero or more instances of the XML object. For example, consider XML data consisting of one outer element and a repeated series of nested elements (e.g., data representing a customer order with the root element being <order> and a nested <item> element for each product in the order). A reference to the root node (order) returns only one element (along with all of its descendants). A reference to the repeated groups of item elements (order.item) returns an XMLList, with a number of entries identical to the number of item elements in the data. Each one of those items, in turn, may have additional child nodes, and so on.

You can reference an individual item of an XMLList through JavaScript array notationsquare brackets and a zero-based integer index, as in:

 order.item[3] 

But that's where the similarity between an XMLList and a JavaScript array end. A special E4X control statement, for-each-in, simplifies iteration through the objects in an XMLList object.

The lines between XML and XMLList objects can be fuzzy at times, and that is intentional. The list of methods of an instance of the XMLList object is a subset of methods for an instance of the XML object. See the description of all methods in the XML object listing, and look for the "Applies To" heading to confirm that the method works with XMLList object instances.


Creating an XMLlist Object

 var myXmlList = new XMLList([XMLList]); 


Properties

None.


Methods

attribute( )
attributes( )
child( )
children( )
comments( )
contains( )
copy( )
descendants( )
elements( )
hasComplexContent( )
hasOwnProperty( )
hasSimpleContent( )
length( )
normalize( )
parent( )
processingInstructions( )
propertyIsEnumerable( )
text( )
toString( )
toXMLString( )
valueOf( )



Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net