Core JavaScript Reference: Chapter 24 - JavaScript: The Definitive Guide
by David FlanaganThis part of the book is a reference that documents the classes, methods, and properties defined by the core JavaScript language. This introduction and the sample reference page that follows explain how to use and get the most out of this section. Take the time to read this material carefully, and you will find it easier to locate and use the information you need!
This excerpt is from JavaScript: The Definitive Guide. The indispensable reference for JavaScript programmers since 1996, JavaScript: The Definitive Guide, 5th Edition is completely revised and expanded to cover JavaScript as it is used in today's Web 2.0 applications.
This reference is arranged alphabetically. The reference pages for
the methods and properties of classes are alphabetized by their full
names, which include the names of the classes that define them. For
example, if you want to read about the replace(
) method of the String class, you would look under String.replace( ), not just replace.
Core JavaScript defines some global functions and properties, such
as eval( ) and NaN. Technically, these are properties of the
global object. Since the global object has no name, however, they are
listed in this reference section under their own unqualified names. For
convenience, the full set of global functions and properties in core
JavaScript is summarized in a special reference page named "Global"
(even though there is no object or class by that name).
Once you've found the page you're looking for, you shouldn't have much difficulty finding the information you need. Still, you'll be able to make better use of this reference if you understand how the reference pages are written and organized. What follows is a sample reference page titled Sample Entry that demonstrates the structure of each reference page and tells you where to find various types of information within the pages. Take the time to read this page before diving into the rest of the reference material.
Name
Sample Entry: how to read these reference pages — Availability: Inherits from
Title and Short Description
Every reference entry begins with a four-part title block like that above. The entries are alphabetized by title. The short description, shown below the title, gives you a quick summary of the item documented in the entry; it can help you quickly decide if you're interested in reading the rest of the page.
Availability
The availability information is shown in the upper-right corner of the title block. In earlier versions of this book, this information told you what version of what web browsers supported the item being documented. Today, most browsers support most of the items documented in this book, and this availability section is more likely to tell you what standard provides the formal specification for the item. You might see "ECMAScript v1" or "DOM Level 2 HTML" here, for example. If the item has been deprecated, that is noted here, as well.
Browser names and version numbers do sometimes appear here, typically when the item being documented is a cutting-edge feature that is not universally adopted or when the item is an Internet Explorer-specific feature.
If an item, such as the History object, has never been standardized but is well supported in browsers that support a particular version of JavaScript, then this section may list that JavaScript version number. The History object, for example, has an availability of "JavaScript 1.0".
If the entry for a method does not include any availability information, that means that it has the same availability as the class that defines the method.
Inherits from
If a class inherits from a superclass or a method overrides a method in a superclass, that information is shown in the lower-right corner of the title block.
As described in Chapter 9, Classes, Constructors, and Prototypes, JavaScript classes can inherit properties and methods from other classes. For example, the String class inherits from Object, and HTMLDocument inherits from Document, which inherits from Node. The entry for String summarizes this inheritance as "Object → String", and the entry for HTMLDocument says "Node → Document → HTMLDocument". When you see this inheritance information, you may also want to look up the listed superclasses.
When a method has the same name as a method in a superclass,
the method overrides the superclass's method. See Array.toString( ) for an example.
Constructor
If the reference page documents a class, and the class has a constructor, this section shows you how to use the constructor method to create instances of the class. Since constructors are a type of method, the Constructor section looks a lot like the Synopsis section of a method's reference page.
Synopsis
Reference pages for functions, methods, and properties have a
Synopsis section that shows how you might use the function, method,
or property in your code. The reference entries in this book use two
different styles of synopses. The entries in the core JavaScript
reference and the client-side entries that document methods (such as
Window methods) that are not related to the DOM use untyped
synopses. For example, the synopsis for the Array.concat( ) method is:
array.concat(value,...)
The italic font indicates text that
is to be replaced with something else.
array should be replaced with a variable
or JavaScript expression that holds or evaluates to an array. And
value is simply a name for an argument to
be passed to the method. This named argument is decribed later in
the synopsis, and that description contains information about the
type and purpose of the argument. The ellipsis (...) indicates that this method can take
any number of value arguments. Because
the terms concat and the open and
close parentheses are not in italics, you
must include them exactly as shown in your JavaScript code.
Many of the methods documented in the client-side JavaScript
section have been standardized by the W3C, and their specifications
include definitive type information for method arguments and method
return values. These entries include this type information in the
synopsis. The synopsis for the Document.getElementById( ) method, for
example is:
Element getElementById(StringelementId);This synopsis uses Java-style syntax to indicate that the
getElementById( ) method returns
an Element object and expects one string argument named
elementId. Because this is a method of
Document, it is implicit that it is invoked on a document, and no
document prefix is
included.
Arguments
If a reference page documents a function, a method, or a class with a constructor method, the Constructor or Synopsis section is followed by an Arguments subsection that describes the arguments to the method, function, or constructor. If there are no arguments, this subsection is simply omitted:
-
arg1 The arguments are described in a list here. This is the description for argument
arg1, for example.-
arg2 And this is the description for argument
arg2.
Constants
Some classes define a set of constants that serve as the
values for a property or as the arguments to a method. The Node
interface, for example, defines important constants to serve as the
set of legal values for its nodeType property. When an interface
defines constants, they are listed and documented in this section.
Note that constants are static properties of the class itself, not
of instances of that class
Properties
If the reference page documents a class, the Properties section lists the properties defined by the class and provides short explanations of each. In Part III, “Core JavaScript Reference”, each property also has a complete reference page of its own. In Part IV, “Client-Side JavaScript Reference”, most properties are fully described in this properties list. The most important or complex client-side properties do have a page of their own, and this is noted here. In Part IV, “Client-Side JavaScript Reference”, the properties of DOM-related classes include type information. Properties of other classes and all properties in Part III, “Core JavaScript Reference” are untyped. The property listing looks like this:
-
prop1 This is a summary of untyped property
prop1. Only the property name is listed above, but this description will tell you the property's type, its purpose or meaning, and whether it is read-only or read/write.-
readonly integer prop2 This is a summary for a typed property
prop2. The property name is included along with its type. This descriptive paragraph explains the purpose of the property.
Methods
The reference page for a class that defines methods includes a Methods section. It is just like the Properties section, except that it summarizes methods instead of properties. All methods also have reference pages of their own. This summary section lists only method names. Argument type and return type information can be found on the method's reference page.
Description
Most reference pages contain a Description section, which is the basic description of the class, method, function, or property that is being documented. This is the heart of the reference page. If you are learning about a class, method, or property for the first time, you may want to skip directly to this section and then go back and look at previous sections, such as Arguments, Properties, and Methods. If you are already familiar with a class, method, or property, you probably won't need to read this section and instead will just want to quickly look up some specific bit of information (for example, from the Arguments or Properties sections).
In some entries, this section is no more than a short paragraph. In others, it may occupy a page or more. For some simple methods, the Arguments and Returns sections document the method sufficiently by themselves, so the Description section is omitted.
Example
Some pages include an example that shows typical usage. Most pages do not contain examples, however; you'll find those in first half of this book.
Name
arguments[ ]: an array of function arguments — ECMAScript v1
Description
The arguments[] array is
defined only within a function body. Within the body of a function,
arguments refers to the Arguments
object for the function. This object has numbered properties
and serves as an array containing all arguments passed to the
function. The arguments
identifier is essentially a local variable automatically declared
and initialized within every function. It refers to an Arguments
object only within the body of a function and is undefined in global
code.
Name
Arguments: arguments and other properties of a function — ECMAScript v1: Object → Arguments
Elements
The Arguments object is defined only within a function body.
Although it is not technically an array, the Arguments object has
numbered properties that function as array elements and a length property that specifies the number
of array elements. Its elements are the values that are passed as
arguments to the function. Element 0 is the first argument, element
1 is the second argument, and so on. All values passed as arguments
become array elements of the Arguments object, whether or not those
arguments are given names in the function declaration.
Properties
-
callee A reference to the function that is currently executing.
-
length The number of arguments passed to the function and the number of array elements in the Arguments object.
Description
When a function is invoked, an Arguments object is created for
it, and the local variable arguments is automatically initialized to
refer to that Arguments object. The main purpose of the Arguments
object is to provide a way to determine how many arguments are
passed to the function and to refer to unnamed arguments. In
addition to the array elements and length property, however, the callee property allows an unnamed function
to refer to itself.
For most purposes, the Arguments object can be thought of as
an array with the addition of the callee property. However, it is not an
instance of Array, and the Arguments.length property does not have
any of the special behaviors of the Array.length property and cannot be used
to change the size of the array.
The Arguments object has one very unusual feature. When a function has named arguments, the array elements of the Arguments object are synonyms for the local variables that hold the function arguments. The Arguments object and the argument names provide two different ways of referring to the same variable. Changing the value of an argument with an argument name changes the value that is retrieved through the Arguments object, and changing the value of an argument through the Arguments object changes the value that is retrieved by the argument name.
Name
Arguments.callee: the function that is currently running — ECMAScript v1
Name
Arguments.length: the number of arguments passed to a function — ECMAScript v1
Description
The length property of the
Arguments object specifies the number of arguments passed to the
current function. This property is defined only within a function
body.
Note that this property specifies the number of arguments
actually passed, not the number expected. See Function.length for the number of declared
arguments. Note also that this property does not have any of the
special behavior of the Array.length property.
Example
// Use an Arguments object to check that correct # of args were passed
function check(args) {
var actual = args.length; // The actual number of arguments
var expected = args.callee.length; // The expected number of arguments
if (actual != expected) { // Throw exception if they don't match
throw new Error("Wrong number of arguments: expected: " +
expected + "; actually passed " + actual);
}
}
// A function that demonstrates how to use the function above
function f(x, y, z) {
check(arguments); // Check for correct number of arguments
return x + y + z; // Now do the rest of the function normally
}Name
Array: built-in support for arrays — ECMAScript v1: Object → Array
Constructor
new Array( )
new Array(size)
new Array(element0,
element1, ...,
elementn)
Arguments
-
size The desired number of elements in the array. The returned array has its
lengthfield set tosize.-
element0, ... elementn An argument list of two or more arbitrary values. When the
Array( )constructor is invoked with these arguments, the newly created array is initialized with the specified argument values as its elements and itslengthfield set to the number of arguments.
Returns
The newly created and initialized array. When Array( ) is invoked with no arguments,
the returned array is empty and has a length field of 0. When invoked with a
single numeric argument, the constructor returns an array with the
specified number of undefined elements. When invoked with any
other arguments, the constructor initializes the array with the
values specified by the arguments. When the Array( ) constructor is called as a
function, without the new
operator, it behaves exactly as it does when called with the
new operator.
Literal Syntax
ECMAScript v3 specifies an array literal syntax. You may also create and initialize an array by placing a comma-separated list of expressions within square brackets. The values of these expressions become the elements of the array. For example:
var a = [1, true, 'abc']; var b = [a[0], a[0]*2, f(x)];
Properties
-
length A read/write integer specifying the number of elements in the array or, when the array does not have contiguous elements, a number one larger than the index of the last element in the array. Changing the value of this property truncates or extends the array.
Methods
-
concat( ) Concatenates elements to an array.
-
join( ) Converts all array elements to strings and concatenates them.
-
pop( ) Removes an item from the end of an array.
-
push( ) Pushes an item to the end of an array.
-
reverse( ) Reverses, in place, the order of the elements of an array.
-
shift( ) Shifts an element off the beginning of an array.
-
slice( ) Returns a subarray slice of an array.
-
sort( ) Sorts, in place, the elements of an array.
-
splice( ) Inserts, deletes, or replaces array elements.
-
toLocaleString( ) Converts an array to a localized string.
-
toString( ) Converts an array to a string.
-
unshift( ) Inserts elements at the beginning of an array.
Description
Arrays are a basic feature of JavaScript and are documented in detail in Chapter 7, Objects and Arrays.
Name
Array.concat( ): concatenate arrays — ECMAScript v3
Description
concat( ) creates and
returns a new array that is the result of concatenating each of its
arguments to array. It does not modify
array. If any of the arguments to
concat( ) is itself an array, the
elements of that array are concatenated, rather than the array
itself.
Name
Array.join( ): concatenate array elements to form a string — ECMAScript v1
Synopsis
array.join( )
array.join(separator)
Description
join( ) converts each
element of an array to a string and then concatenates those strings,
inserting the specified separator string
between the elements. It returns the resulting string.
You can perform a conversion in the opposite
direction—splitting a string into array elements—with the split( ) method of the String object. See
String.split( ) for
details.
Name
Array.length: the size of an array — ECMAScript v1
Description
The length property of an
array is always one larger than the index of the highest element
defined in the array. For traditional "dense" arrays that have
contiguous elements and begin with element 0, the length property specifies the number of
elements in the array.
The length property of an
array is initialized when the array is created with the Array( ) constructor method. Adding new
elements to an array updates the length, if necessary:
a = new Array( ); // a.length initialized to 0
b = new Array(10); // b.length initialized to 10
c = new Array("one", "two", "three"); // c.length initialized to 3
c[3] = "four"; // c.length updated to 4
c[10] = "blastoff"; // c.length becomes 11You can set the value of the length property to change the size of an
array. If you set length to be
smaller than its previous value, the array is truncated, and
elements at the end are lost. If you set length to be larger than its previous
value, the array becomes bigger, and the new elements added at the
end of the array have the undefined value.
Name
Array.pop( ): remove and return the last element of an array — ECMAScript v3
Description
pop( ) deletes the last
element of array, decrements the array
length, and returns the value of the element that it deleted. If the
array is already empty, pop( )
does not change the array and returns the undefined value.
Example
pop( ), and its companion
method push( ), provide the
functionality of a first-in, last-out stack. For example:
var stack = []; // stack: [] stack.push(1, 2); // stack: [1,2] Returns 2 stack.pop( ); // stack: [1] Returns 2 stack.push([4,5]); // stack: [1,[4,5]] Returns 2 stack.pop( ) // stack: [1] Returns [4,5] stack.pop( ); // stack: [] Returns 1
Name
Array.push( ): append elements to an array — ECMAScript v3
Name
Array.reverse( ): reverse the elements of an array — ECMAScript v1
Description
The reverse( ) method of an
Array object reverses the order of the elements of an array. It does
this in place: it rearranges the elements of
the specified array without creating a
new array. If there are multiple references to
array, the new order of the array
elements is visible through all references.
Name
Array.shift( ): shift array elements down — ECMAScript v3
Description
shift( ) removes and
returns the first element of array,
shifting all subsequent elements down one place to occupy the newly
vacant space at the start of the array. If the array is empty,
shift( ) does nothing and returns
the undefined value. Note that
shift( ) does not create a new
array; instead, it modifies array
directly.
shift( ) is similar to
Array.pop( ), except it operates
on the beginning of an array rather than the end. shift( ) is often used in conjunction with
unshift( ).
Name
Array.slice( ): return a portion of an array — ECMAScript v3
Synopsis
array.slice(start,
end)
Arguments
-
start The array index at which the slice is to begin. If negative, this argument specifies a position measured from the end of the array. That is, −1 indicates the last element, −2 indicates the next from the last element, and so on.
-
end The array index immediately after the end of the slice. If not specified, the slice includes all array elements from the
startto the end of the array. If this argument is negative, it specifies an array element measured from the end of the array.
Description
slice( ) returns a slice,
or subarray, of array. The returned array
contains the element specified by start
and all subsequent elements up to, but not including, the element
specified by end. If
end is not specified, the returned array
contains all elements from the start to
the end of array.
Note that slice( ) does not
modify the array. If you want to actually remove a slice of an
array, use Array.splice(
).
Name
Array.sort( ): sort the elements of an array — ECMAScript v1
Description
The sort( ) method sorts
the elements of array in place: no copy
of the array is made. If sort( )
is called with no arguments, the elements of the array are arranged
in alphabetical order (more precisely, the order determined by the
character encoding). To do this, elements are first converted to
strings, if necessary, so that they can be compared.
If you want to sort the array elements in some other order,
you must supply a comparison function that compares two values and
returns a number indicating their relative order. The comparison
function should take two arguments, a and
b, and should return one of the
following:
A value less than zero, if, according to your sort criteria,
ais less thanband should appear beforebin the sorted array.Zero, if
aandbare equivalent for the purposes of this sort.A value greater than zero, if
ais greater thanbfor the purposes of the sort.
Note that undefined elements of an array are always sorted to
the end of the array. This is true even if you provide a custom
ordering function: undefined values are never passed to the
orderfunc you supply.
Example
The following code shows how you might write a comparison function to sort an array of numbers in numerical, rather than alphabetical order:
// An ordering function for a numerical sort
function numberorder(a, b) { return a - b; }
a = new Array(33, 4, 1111, 222);
a.sort( ); // Alphabetical sort: 1111, 222, 33, 4
a.sort(numberorder); // Numerical sort: 4, 33, 222, 1111Name
Array.splice( ): insert, remove, or replace array elements — ECMAScript v3
Synopsis
array.splice(start,
deleteCount,
value, ...)
Arguments
-
start The array element at which the insertion and/or deletion is to begin.
-
deleteCount The number of elements, starting with and including
start, to be deleted fromarray. Specify 0 to insert elements without deleting any.-
value, ... Zero or more values to be inserted into
array, beginning at the index specified bystart.
Description
splice( ) deletes zero or
more array elements starting with and including the element
start and replaces them with zero or more
values specified in the argument list. Array elements that appear
after the insertion or deletion are moved as necessary so that they
remain contiguous with the rest of the array. Note that, unlike the
similarly named slice( ),
splice( ) modifies
array directly.
Name
Array.toLocaleString( ): convert an array to a localized string — ECMAScript v1: Overrides Object.toLocaleString( )
Name
Array.toString( ): convert an array to a string — ECMAScript v1: Overrides Object.toString( )
Description
The toString( ) method of
an array converts an array to a string and returns the string. When
an array is used in a string context, JavaScript automatically
converts it to a string by calling this method. On some occasions,
however, you may want to call toString(
) explicitly.
toString( ) converts an
array to a string by first converting each array element to strings
(by calling its toString( )
method). Once each element is converted to a string, toString( ) outputs them in a
comma-separated list. This return value is the same string that
would be returned by the join( )
method with no arguments.
Name
Array.unshift( ): insert elements at the beginning of an array — ECMAScript v3
Description
unshift( ) inserts its
arguments at the beginning of array,
shifting the existing elements to higher indexes to make room. The
first argument to shift( )
becomes the new element 0 of the array; the second argument, if any,
becomes the new element 1; and so on. Note that unshift( ) does not create a new array; it
modifies array directly.
Name
Boolean: support for boolean values — ECMAScript v1: Object → Boolean
Constructor
new Boolean(value) // Constructor function Boolean(value) // Conversion function
Returns
When invoked as a constructor with the new operator, Boolean( ) converts its argument to a
boolean value and returns a Boolean object that contains that
value. When invoked as a function, without the new operator, Boolean( ) simply converts its argument
to a primitive boolean value and returns that value.
The values 0, NaN,
null, the empty string "", and the undefined value are all converted to
false. All other primitive
values, except false (but
including the string "false"), and all objects and arrays are
converted to true.
Methods
-
toString( ) Returns "true" or "false", depending on the boolean value represented by the Boolean object.
-
valueOf( ) Returns the primitive boolean value contained in the Boolean object.
Description
Boolean values are a fundamental datatype in JavaScript. The
Boolean object is an object wrapper around the boolean value. This
Boolean object type exists primarily to provide a toString( ) method to convert boolean
values to strings. When the toString(
) method is invoked to convert a boolean value to a string
(and it is often invoked implicitly by JavaScript), JavaScript
internally converts the boolean value to a transient Boolean object,
on which the method can be invoked.
Name
Boolean.toString( ): convert a boolean value to a string — ECMAScript v1: Overrides Object.toString( )
Name
Boolean.valueOf( ): the boolean value of a Boolean object — ECMAScript v1: Overrides Object.valueOf( )
Name
Date: manipulate dates and times — ECMAScript v1: Object → Date
Constructor
new Date( ) new Date(milliseconds) new Date(datestring) new Date(year,month,day,hours,minutes,seconds,ms)
With no arguments, the Date(
) constructor creates a Date object set to the current date and time. When one numeric
argument is passed, it is taken as the internal numeric
representation of the date in milliseconds, as returned by the
getTime( ) method. When one
string argument is passed, it is a string representation of a date,
in the format accepted by the Date.parse(
) method. Otherwise, the constructor is passed between two
and seven numeric arguments that specify the individual fields of
the date and time. All but the first two arguments—the year and
month fields—are optional. Note that these date and time fields are
specified using local time, not Coordinated Universal Time (UTC) (which is
similar to Greenwich Mean Time [GMT]). See the static Date.UTC( ) method for an
alternative.
Date( ) may also be called
as a function, without the new
operator. When invoked in this way, Date(
) ignores any arguments passed to it and returns a string
representation of the current date and time.
Arguments
-
milliseconds The number of milliseconds between the desired date and midnight on January 1, 1970 (UTC). For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
-
datestring A single argument that specifies the date and, optionally, the time as a string. The string should be in a format accepted by
Date.parse( ).-
year The year, in four-digit format. For example, specify
2001for the year 2001. For compatibility with early implementations of JavaScript, if this argument is between 0 and 99, 1900 is added to it.-
month The month, specified as an integer from 0 (January) to 11 (December).
-
day The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value. Optional.
-
hours The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.). Optional.
-
minutes The minutes in the hour, specified as an integer from 0 to 59. Optional.
-
seconds The seconds in the minute, specified as an integer from 0 to 59. Optional.
-
ms The milliseconds in the second, specified as an integer from 0 to 999. Optional.
Methods
The Date object has no properties that can be read and
written directly; instead, all access to date and time values is
done through methods. Most methods of the Date object come in two
forms: one that operates using local time and one that operates using universal (UTC or GMT)
time. If a method has "UTC" in its name, it operates using universal
time. These pairs of methods are listed together below. For example,
the listing for get[UTC]Day( )
refers to both the methods getDay(
) and getUTCDay(
).
Date methods may be invoked only on Date objects, and they throw a TypeError exception if you attempt to invoke them on any other type of object:
-
get[UTC]Date( ) Returns the day of the month of a Date object, in local or universal time.
-
get[UTC]Day( ) Returns the day of the week of a Date object, in local or universal time.
-
get[UTC]FullYear( ) Returns the year of the date in full four-digit form, in local or universal time.
-
get[UTC]Hours( ) Returns the hours field of a Date object, in local or universal time.
-
get[UTC]Milliseconds( ) Returns the milliseconds field of a Date object, in local or universal time.
-
get[UTC]Minutes( ) Returns the minutes field of a Date object, in local or universal time.
-
get[UTC]Month( ) Returns the month field of a Date object, in local or universal time.
-
get[UTC]Seconds( ) Returns the seconds field of a Date object, in local or universal time.
-
getTime( ) Returns the internal, millisecond representation of a Date object. Note that this value is independent of time zone, and therefore, there is not a separate
getUTCTime( )method.-
getTimezoneOffset( ) Returns the difference, in minutes, between the local and UTC representations of this date. Note that the value returned depends on whether daylight saving time is or would be in effect at the specified date.
-
getYear( ) Returns the year field of a Date object. Deprecated in favor of
getFullYear( ).-
set[UTC]Date( ) Sets the day of the month field of the date, using local or universal time.
-
set[UTC]FullYear( ) Sets the year (and optionally month and day) field of the date, using local or universal time.
-
set[UTC]Hours( ) Sets the hour field (and optionally the minutes, seconds, and milliseconds fields) of the date, using local or universal time.
-
set[UTC]Milliseconds( ) Sets the milliseconds field of a date, using local or universal time.
-
set[UTC]Minutes( ) Sets the minutes field (and optionally the seconds and milliseconds fields) of a date, using local or universal time.
-
set[UTC]Month( ) Sets the month field (and optionally the day of the month) of a date, using local or universal time.
-
set[UTC]Seconds( ) Sets the seconds field (and optionally the milliseconds field) of a date, using local or universal time.
-
setTime( ) Sets the fields of a Date object using the millisecond format.
-
setYear( ) Sets the year field of a Date object. Deprecated in favor of
setFullYear( ).-
toDateString( ) Returns a string that represents the date portion of the date, expressed in the local time zone.
-
toGMTString( ) Converts a Date to a string, using the GMT time zone. Deprecated in favor of
toUTCString( ).-
toLocaleDateString( ) Returns a string that represents the date portion of the date, expressed in the local time zone, using the local date formatting conventions.
-
toLocaleString( ) Converts a Date to a string, using the local time zone and the local date formatting conventions.
-
toLocaleTimeString( ) Returns a string that represents the time portion of the date, expressed in the local time zone, using the local time formatting conventions.
-
toString( ) Converts a Date to a string using the local time zone.
-
toTimeString( ) Returns a string that represents the time portion of the date, expressed in the local time zone.
-
toUTCString( ) Converts a Date to a string, using universal time.
-
valueOf( ) Converts a Date to its internal millisecond format.
Static Methods
In addition to the many instance methods listed
previously, the Date object also defines two static methods. These
methods are invoked through the Date(
) constructor itself, not through individual Date
objects:
-
Date.parse( ) Parses a string representation of a date and time and returns the internal millisecond representation of that date.
-
Date.UTC( ) Returns the millisecond representation of the specified UTC date and time.
Description
The Date object is a datatype built into the JavaScript
language. Date objects are created with the new Date( ) syntax shown earlier.
Once a Date object is created, a number of methods allow you
to operate on it. Most methods simply allow you to get and set the
year, month, day, hour, minute, second, and millisecond fields of
the object, using either local time or UTC (universal, or GMT) time.
The toString( ) method and its
variants convert dates to human-readable strings. getTime( ) and setTime( ) convert to and from the
internal representation of the Date object—the number of
milliseconds since midnight (GMT) on January 1, 1970. In this
standard millisecond format, a date and time are represented by a
single integer, which makes date arithmetic particularly easy. The
ECMAScript standard requires the Date object to be able to represent
any date and time, to millisecond precision, within 100 million days
before or after 1/1/1970. This is a range of plus or minus 273,785
years, so the JavaScript clock will not "roll over" until the year
275755.
Examples
Once you create a Date object, there are a variety of methods you can use to operate on it:
d = new Date( ); // Get the current date and time
document.write('Today is: " + d.toLocaleDateString( ) + '. '); // Display date
document.write('The time is: ' + d.toLocaleTimeString( )); // Display time
var dayOfWeek = d.getDay( ); // What weekday is it?
var weekend = (dayOfWeek == 0) || (dayOfWeek == 6); // Is it a weekend?Another common use of the Date object is to subtract the millisecond representations of the current time from some other time to determine the difference between the two times. The following client-side example shows two such uses:
<script language="JavaScript">
today = new Date( ); // Make a note of today's date
christmas = new Date( ); // Get a date with the current year
christmas.setMonth(11); // Set the month to December...
christmas.setDate(25); // and the day to the 25th
// If Christmas hasn't already passed, compute the number of
// milliseconds between now and Christmas, convert this
// to a number of days and print a message
if (today.getTime() < christmas.getTime( )) {
difference = christmas.getTime() - today.getTime( );
difference = Math.floor(difference / (1000 * 60 * 60 * 24));
document.write('Only ' + difference + ' days until Christmas!<p>');
}
</script>
// ... rest of HTML document here ...
<script language="JavaScript">
// Here we use Date objects for timing
// We divide by 1000 to convert milliseconds to seconds
now = new Date( );
document.write('<p>It took ' +
(now.getTime()-today.getTime( ))/1000 +
'seconds to load this page.');
</script>Name
Date.getTime( ): return a Date in milliseconds — ECMAScript v1
Description
getTime( ) converts a date
and time to a single integer. This is useful when you want to
compare two Date objects or to determine the time elapsed between
two dates. Note that the millisecond representation of a date is
independent of the time zone, so there is no getUTCTime( ) method in addition to this
one. Don't confuse this getTime(
) method with the getDay(
) and getDate( )
methods, which return the day of the week and the day of the month,
respectively.
Date.parse( ) and Date.UTC( ) allow you to convert a date
and time specification to a millisecond representation without going
through the overhead of first creating a Date object.
Name
Date.getTimezoneOffset( ): determine the offset from GMT — ECMAScript v1
Description
getTimezoneOffset( )
returns the number of minutes difference between the GMT or UTC time
and the local time. In effect, this function tells you what time
zone the JavaScript code is running in and whether or not daylight
saving time is (or would be) in effect at the specified
date.
The return value is measured in minutes, rather than hours, because some countries have time zones that are not at even one-hour intervals.
Name
Date.getUTCDate( ): return the day-of-the-month field of a Date (universal time) — ECMAScript v1
Name
Date.getUTCMilliseconds( ): return the milliseconds field of a Date (universal time) — ECMAScript v1
Name
Date.getUTCMonth( ): return the month-of-the-year field of a Date (universal time) — ECMAScript v1
Name
Date.parse( ): parse a date/time string — ECMAScript v1
Description
Date.parse( )is a static
method of Date. It is always invoked through the Date constructor as Date.parse( ), not through a Date object
as date .parse(
). Date.parse( ) takes
a single string argument. It parses the date contained in this
string and returns it in millisecond format, which can be used
directly, used to create a new Date object, or used to set the date
in an existing Date object with Date.setTime( ).
The ECMAScript standard does not specify the format of the
strings that can be parsed by Date.parse(
) except to say that this method can parse the strings
returned by the Date.toString( )
and Date.toUTCString( ) methods.
Unfortunately, these functions format dates in an
implementation-dependent way, so it is not, in general, possible to
write dates in a way that is guaranteed to be understood by all
JavaScript implementations.
Name
Date.setFullYear( ): set the year and, optionally, the month and date fields of a Date — ECMAScript v1
Synopsis
date.setFullYear(year)
date.setFullYear(year,
month)
date.setFullYear(year,
month,
day)
Arguments
-
year The year, expressed in local time, to be set in
date. This argument should be an integer that includes the century, such as 1999; it should not be an abbreviation, such as 99.-
month An optional integer between 0 and 11 that is used as the new value (in local time) of the month field of
date.-
day An optional integer between 1 and 31 that is used as the new value (in local time) of the day-of-the-month field of
date.
Name
Date.setHours( ): set the hours, minutes, seconds, and milliseconds fields of a Date — ECMAScript v1
Synopsis
date.setHours(hours)
date.setHours(hours,
minutes)
date.setHours(hours,
minutes,
seconds)
date.setHours(hours,
minutes,
seconds,
millis)
Arguments
-
hours An integer between 0 (midnight) and 23 (11 p.m.) local time that is set as the new hours value of
date.-
minutes An optional integer, between 0 and 59, that is used as the new value (in local time) of the minutes field of
date. This argument is not supported prior to ECMAScript standardization.-
seconds An optional integer, between 0 and 59, that is used as the new value (in local time) of the seconds field of
date. This argument is not supported prior to ECMAScript standardization.-
millis An optional integer, between 0 and 999, that is used as the new value (in local time) of the milliseconds field of
date. This argument is not supported prior to ECMAScript standardization.
Name
Date.setMinutes( ): set the minutes, seconds, and milliseconds fields of a Date — ECMAScript v1
Synopsis
date.setMinutes(minutes)
date.setMinutes(minutes,
seconds)
date.setMinutes(minutes,
seconds,
millis)
Arguments
-
minutes An integer between 0 and 59 that is set as the minutes value (in local time) of the Date object
date.-
seconds An optional integer, between 0 and 59, that is used as the new value (in local time) of the seconds field of
date. This argument is not supported prior to ECMAScript standardization.-
millis An optional integer, between 0 and 999, that is used as the new value (in local time) of the milliseconds field of
date. This argument is not supported prior to ECMAScript standardization.
Name
Date.setMonth( ): set the month and day fields of a Date — ECMAScript v1
Synopsis
date.setMonth(month)
date.setMonth(month,
day)
Arguments
-
month An integer between 0 ( January) and 11 (December) that is set as the month value (in local time) for the Date object
date. Note that months are numbered beginning with 0, while days within the month are numbered beginning with 1.-
day An optional integer between 1 and 31 that is used as the new value (in local time) of the day-of-the-month field of
date. This argument is not supported prior to ECMAScript standardization.
Name
Date.setSeconds( ): set the seconds and milliseconds fields of a Date — ECMAScript v1
Synopsis
date.setSeconds(seconds)
date.setSeconds(seconds,
millis)
Arguments
-
seconds An integer between 0 and 59 that is set as the seconds value for the Date object
date.-
millis An optional integer, between 0 and 999, that is used as the new value (in local time) of the milliseconds field of
date. This argument is not supported prior to ECMAScript standardization.
Name
Date.setTime( ): set a Date in milliseconds — ECMAScript v1
Synopsis
date.setTime(milliseconds)
Arguments
-
milliseconds The number of milliseconds between the desired date and time and midnight GMT on January 1, 1970. A millisecond value of this type may also be passed to the
Date( )constructor and may be obtained by calling theDate.UTC( )andDate.parse( )methods. Representing a date in this millisecond format makes it independent of time zone.
Name
Date.setUTCFullYear( ): set the year, month, and day fields of a Date (universal time) — ECMAScript v1
Synopsis
date.setUTCFullYear(year)
date.setUTCFullYear(year,
month)
date.setUTCFullYear(year,
month,
day)
Arguments
-
year The year, expressed in universal time, to be set in
date. This argument should be an integer that includes the century, such as 1999, not an abbreviation, such as 99.-
month An optional integer between 0 and 11 that is used as the new value (in universal time) of the month field of
date. Note that months are numbered beginning with 0, while days within the month are numbered beginning with 1.-
day An optional integer between 1 and 31 that is used as the new value (in universal time) of the day-of-the-month field of
date.
Name
Date.setUTCHours( ): set the hours, minutes, seconds, and milliseconds fields of a Date (universal time) — ECMAScript v1
Synopsis
date.setUTCHours(hours)
date.setUTCHours(hours,
minutes)
date.setUTCHours(hours,
minutes,
seconds)
date.setUTCHours(hours,
minutes,
seconds,
millis)
Arguments
-
hours The hours field, expressed in universal time, to be set in
date. This argument should be an integer between 0 (midnight) and 23 (11 p.m.).-
minutes An optional integer, between 0 and 59, that is used as the new value (in universal time) of the minutes field of
date.-
seconds An optional integer, between 0 and 59, that is used as the new value (in universal time) of the seconds field of
date.-
millis An optional integer, between 0 and 999, that is used as the new value (in universal time) of the milliseconds field of
date.
Name
Date.setUTCMilliseconds( ): set the milliseconds field of a Date (universal time) — ECMAScript v1
Name
Date.setUTCMinutes( ): set the minutes, seconds, and milliseconds fields of a Date (universal time) — ECMAScript v1
Synopsis
date.setUTCMinutes(minutes)
date.setUTCMinutes(minutes,
seconds)
date.setUTCMinutes(minutes,
seconds,
millis)
Arguments
-
minutes The minutes field, expressed in universal time, to be set in
date. This argument should be an integer between 0 and 59.-
seconds An optional integer between 0 and 59 that is used as the new value (in universal time) of the seconds field of
date.-
millis An optional integer between 0 and 999 that is used as the new value (in universal time) of the milliseconds field of
date.
Name
Date.setUTCMonth( ): set the month and day fields of a Date (universal time) — ECMAScript v1
Synopsis
date.setUTCMonth(month)
date.setUTCMonth(month,
day)
Arguments
-
month The month, expressed in universal time, to be set in
date. This argument should be an integer between 0 (January) and 11 (December). Note that months are numbered beginning with 0, while days within the month are numbered beginning with 1.-
day An optional integer between 1 and 31 that is used as the new value (in universal time) of the day-of-the-month field of
date.
Name
Date.setUTCSeconds( ): set the seconds and milliseconds fields of a Date (universal time) — ECMAScript v1
Synopsis
date.setUTCSeconds(seconds)
date.setUTCSeconds(seconds,
millis)
Name
Date.setYear( ): set the year field of a Date — ECMAScript v1; deprecated by ECMAScript v3
Name
Date.toDateString( ): return the date portion of a Date as a string — ECMAScript v3
Name
Date.toGMTString( ): convert a Date to a universal time string — ECMAScript v1; deprecated by ECMAScript v3
Name
Date.toLocaleDateString( ): return the date portion of a Date as a locally formatted string — ECMAScript v3
Name
Date.toLocaleString( ): convert a Date to a locally formatted string — ECMAScript v1
Usage
toLocaleString( ) converts
a date to a string, using the local time zone. This method also uses
local conventions for date and time formatting, so the format may
vary from platform to platform and from country to country. toLocaleString( ) returns a string
formatted in what is likely the user's preferred date and time
format.
Name
Date.toLocaleTimeString( ): return the time portion of a Date as a locally formatted string — ECMAScript v3
Name
Date.toString( ): convert a Date to a string — ECMAScript v1: Overrides Object.toString( )
Name
Date.toTimeString( ): return the time portion of a Date as a string — ECMAScript v3
Name
Date.toUTCString( ): convert a Date to a string (universal time) — ECMAScript v1
Name
Date.UTC( ): convert a Date specification to milliseconds — ECMAScript v1
Synopsis
Date.UTC(year,month,day,hours,minutes,seconds,ms)
Arguments
-
year The year in four-digit format. If this argument is between 0 and 99, inclusive, 1900 is added to it and it is treated as a year between 1900 and 1999.
-
month The month, specified as an integer from 0 (January) to 11 (December).
-
day The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value. This argument is optional.
-
hours The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.). This argument is optional.
-
minutes The minutes in the hour, specified as an integer from 0 to 59. This argument is optional.
-
seconds The seconds in the minute, specified as an integer from 0 to 59. This argument is optional.
-
ms The number of milliseconds, specified as an integer from 0 to 999. This argument is optional and is ignored prior to ECMAScript standardization.
Description
Date.UTC( ) is a
static method; it is invoked through the Date( ) constructor, not through an
individual Date object.
The arguments to Date.UTC(
) specify a date and time and are understood to be in UTC;
they are in the GMT time zone. The specified UTC time is converted
to the millisecond format, which can be used by the Date( ) constructor method and by the
Date.setTime( ) method.
The Date( ) constructor
method can accept date and time arguments identical to those that
Date.UTC( ) accepts. The
difference is that the Date( )
constructor assumes local time, while Date.UTC( ) assumes universal time (GMT).
To create a Date object using a UTC time specification, you can use
code like this:
d = new Date(Date.UTC(1996, 4, 8, 16, 30));
Name
Date.valueOf( ): convert a Date to millisecond representation — ECMAScript v1: Overrides Object.valueOf( )
Name
decodeURI( ): unescape characters in a URI — ECMAScript v3
Synopsis
decodeURI(uri)Name
decodeURIComponent( ): unescape characters in a URI component — ECMAScript v3
Synopsis
decodeURI(s)Name
encodeURI( ): escape characters in a URI — ECMAScript v3
Description
encodeURI( ) is a global
function that returns an encoded copy of its
uri argument. ASCII letters and digits
are not encoded, nor are the following ASCII punctuation
characters:
- _ . ! ~ * ' ( )
Because encodeURI( ) is
intended to encode complete URIs, the following ASCII punctuation
characters, which have special meaning in URIs, are not escaped
either:
; / ? : @ & = + $ , #
Any other characters in uri are
replaced by converting each character to its UTF-8 encoding and then
encoding each of the resulting one, two, or three bytes with a
hexadecimal escape sequence of the form %xx. In this encoding scheme, ASCII
characters are replaced with a single %xx escape, characters with encodings
between \u0080 and \u07ff are replaced with two escape
sequences, and all other 16-bit Unicode characters are replaced with
three escape sequences.
If you use this method to encode a URI, you should be certain
that none of the components of the URI (such as the query string)
contain URI separator characters such as ? and #. If the components
have to contain these characters, you should encode each component
separately with encodeURIComponent(
).
Use decodeURI( ) to reverse
the encoding applied by this method. Prior to ECMAScript v3, you can
use escape( ) and unescape( ) methods (which are now
deprecated) to perform a similar kind of encoding and
decoding.
Name
encodeURIComponent( ): escape characters in a URI component — ECMAScript v3
Description
encodeURIComponent( ) is a
global function that returns an encoded copy of its
s argument. ASCII letters and digits are
not encoded, nor are the following ASCII punctuation
characters:
- _ . ! ~ * ' ( )
All other characters, including punctuation characters such as
/, :, and # that serve to separate the various components of a URI,
are replaced with one or more hexadecimal escape sequences. See
encodeURI( ) for a description of
the encoding scheme used.
Note the difference between encodeURIComponent( ) and encodeURI( ): encodeURIComponent( ) assumes that its
argument is a portion (such as the protocol, hostname, path, or
query string) of a URI. Therefore it escapes the punctuation
characters that are used to separate the portions of a URI.
Name
Error: a generic exception — ECMAScript v3: Object → Error
Constructor
new Error( )
new
Error(message)
Returns
A newly constructed Error object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the Error( )
constructor is called as a function, without the new operator, it behaves just as it does
when called with the new
operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string.
-
name A string that specifies the type of the exception. For instances of the Error class and all of its subclasses, this property specifies the name of the constructor used to create the instance.
Description
Instances of the Error class represent errors or exceptions
and are typically used with the throw and try/catch statements. The name property specifies the type of the
exception, and the message
property can provide human-readable details about the
exception.
The JavaScript interpreter never throws Error objects directly; instead, it throws instances of one of the Error subclasses, such as SyntaxError or RangeError. In your own code, you may find it convenient to throw Error objects to signal exceptions, or you may prefer to simply throw an error message or error code as a primitive string or number value.
Note that the ECMAScript specification defines a toString( ) method for the Error class (it
is inherited by each of the subclasses of Error) but that it does
not require this toString( )
method to return a string that contains the contents of the message property. Therefore, you should
not expect the toString( ) method
to convert an Error object to a meaningful, human-readable string.
To display an error message to a user, you should explicitly use the
name and message properties of the Error
object.
Examples
You might signal an exception with code like the following:
function factorial(x) {
if (x < 0) throw new Error("factorial: x must be >= 0");
if (x <= 1) return 1; else return x * factorial(x-1);
}And if you catch an exception, you might display its to the
user with code like the following (which uses the client-side
Window.alert( ) method):
try { &*(&/* an error is thrown here */ }
catch(e) {
if (e instanceof Error) { // Is it an instance of Error or a subclass?
alert(e.name + ": " + e.message);
}
}Name
Error.message: a human-readable error message — ECMAScript v3
Description
The message property of an
Error object (or of an instance of any subclass of Error) is
intended to contain a human-readable string that provides details
about the error or exception that occurred. If a
message argument is passed to the
Error( ) constructor, this
message becomes the value of the message property. If no
message argument is passed, an Error
object inherits an implementation-defined default value (which may
be the empty string) for this property.
Name
Error.name: the type of an error — ECMAScript v3
Description
The name property of an
Error object (or of an instance of any subclass of Error) specifies
the type of error or exception that occurred. All Error objects
inherit this property from their constructor. The value of the
property is the same as the name of the constructor. Thus
SyntaxError objects have a name
property of "SyntaxError", and EvalError objects have a name of "EvalError".
Name
Error.toString( ): convert an Error object to a string — ECMAScript v3: Overrides Object.toString( )
Name
escape( ): encode a string — ECMAScript v1; deprecated in ECMAScript v3
Description
escape( ) is a global
function. It returns a new string that contains an encoded version
of s. The string
s itself is not modified.
escape( ) returns a string
in which all characters of s other than
ASCII letters, digits, and the punctuation characters @, *, _, +, -,
., and / have been replaced by escape sequences of the form % xx or
%u
xxxx (where x
represents a hexadecimal digit). Unicode characters \u0000 to \u00ff are replaced with the % xx escape
sequence, and all other Unicode characters are replaced with the
%u
xxxx sequence.
Use the unescape( )
function to decode a string encoded with escape( ).
Although the escape( )
function was standardized in the first version of ECMAScript, it was
deprecated and removed from the standard by ECMAScript v3.
Implementations of ECMAScript are likely to implement this function,
but they are not required to. You should use encodeURI( ) and encodeURIComponent( ) instead of escape( ).
Name
eval( ): execute JavaScript code from a string — ECMAScript v1
Synopsis
eval(code)
Arguments
-
code A string that contains the JavaScript expression to be evaluated or the statements to be executed.
Throws
- SyntaxError
Indicates that
codedoes not contain legal JavaScript.- EvalError
Indicates that
eval( )was called illegally, through an identifier other than "eval", for example. See the restrictions on this function described in the next section.- Other exception
If the JavaScript code passed to
eval( )generates an exception,eval( )passes that exception on to the caller.
Description
eval( ) is a global method
that evaluates a string of JavaScript code in the current lexical
scope. If code contains an expression,
eval evaluates the expression and
returns its value. If code contains a
JavaScript statement or statements, eval(
) executes those statements and returns the value, if any,
returned by the last statement. If code
does not return any value, eval(
) returns undefined.
Finally, if code throws an exception,
eval( ) passes that exception on
to the caller.
eval( ) provides a very
powerful capability to the JavaScript language, but its use is
infrequent in real-world programs. Obvious uses are to write
programs that act as recursive JavaScript interpreters and to write
programs that dynamically generate and evaluate JavaScript
code.
Most JavaScript functions and methods that expect string
arguments accept arguments of other types as well and simply convert
those argument values to strings before proceeding. eval( ) does not behave like this. If the
code argument is not a primitive string,
it is simply returned unchanged. Be careful, therefore, that you do
not inadvertently pass a String object to eval( ) when you intended to pass a
primitive string value.
For purposes of implementation efficiency, the ECMAScript v3
standard places an unusual restriction on the use of eval( ). An ECMAScript implementation is
allowed to throw an EvalError exception if you attempt to overwrite
the eval property or if you
assign the eval( ) method to
another property and attempt to invoke it through that
property.
Example
eval("1+2"); // Returns 3
// This code uses client-side JavaScript methods to prompt the user to
// enter an expression and to display the results of evaluating it.
// See the client-side methods Window.alert() and Window.prompt( ) for details.
try {
alert("Result: " + eval(prompt("Enter an expression:","")));
}
catch(exception) {
alert(exception);
}
var myeval = eval; // May throw an EvalError
myeval("1+2"); // May throw an EvalErrorName
EvalError: thrown when eval( ) is used improperly — ECMAScript v3: Object → Error → EvalError
Constructor
new EvalError( )
new EvalError(message)
Returns
A newly constructed EvalError object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the EvalError( )
constructor is called as a function without the new operator, it behaves just as it does
when called with the new
operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string. See
Error.messagefor details.-
name A string that specifies the type of the exception. All EvalError objects inherit the value "EvalError" for this property.
Name
Function: a JavaScript function — ECMAScript v1: Object → Function
Synopsis
functionfunctionname(argument_name_list) // Function definition statement {body} function (argument_name_list) {body} // Unnamed function literalfunctionname(argument_value_list) // Function invocation
Constructor
new
Function(argument_names...,
body)
Arguments
-
argument_names... Any number of string arguments, each naming one or more arguments of the Function object being created.
-
body A string that specifies the body of the function. It may contain any number of JavaScript statements, separated with semicolons, and may refer to any of the argument names specified by previous arguments to the constructor.
Properties
-
arguments[] An array of arguments that were passed to the function. Deprecated.
-
caller A reference to the Function object that invoked this one, or
nullif the function was invoked from top-level code. Deprecated.-
length The number of named arguments specified when the function was declared.
-
prototype An object which, for a constructor function, defines properties and methods shared by all objects created with that constructor function.
Methods
-
apply( ) Invokes a function as a method of a specified object, passing a specified array of arguments.
-
call( ) Invokes a function as a method of a specified object, passing the specified arguments.
-
toString( ) Returns a string representation of the function.
Description
A function is a fundamental datatype in JavaScript. Chapter 8, Functions explains how to define and use
functions, and Chapter 9, Classes, Constructors, and Prototypes covers the
related topics of methods, constructors, and the prototype property of functions. See those
chapters for complete details. Note that although function objects
may be created with the Function(
) constructor described here, this is not efficient, and
the preferred way to define functions, in most cases, is with a
function definition statement or a function literal.
In JavaScript 1.1 and later, the body of a function is
automatically given a local variable, named arguments, that refers to an Arguments
object. This object is an array of the values passed as arguments to
the function. Don't confuse this with the deprecated arguments[] property listed earlier. See
the Arguments reference page for
details.
Name
Function.apply( ): invoke a function as a method of an object — ECMAScript v3
Synopsis
function.apply(thisobj,
args)
Description
apply( ) invokes the
specified function as if it were a method
of thisobj, passing it the arguments
contained in the args array. It returns
the value returned by the function invocation. Within the body of
the function, the this keyword
refers to the thisobj object.
The args argument must be an array
or an Arguments object. Use Function.call(
) instead if you want to specify the arguments to pass to
the function individually instead of as array elements.
Example
// Apply the default Object.toString( ) method to an object that // overrides it with its own version of the method. Note no arguments. Object.prototype.toString.apply(o); // Invoke the Math.max( ) method with apply to find the largest // element in an array. Note that first argument doesn't matter // in this case. var data = [1,2,3,4,5,6,7,8]; Math.max.apply(null, data);
Name
Function.arguments[]: arguments passed to a function — ECMAScript v1; deprecated by ECMAScript v3
Description
The arguments property of a
Function object is an array of the arguments that are passed to a
function. It is defined only while the function is executing.
arguments.length specifies the
number of elements in the array.
This property is deprecated in favor of the Arguments object.
Although ECMAScript v1 supports the Function.arguments property, it has been
removed from ECMAScript v3 and conforming implementations may no
longer support this property. Therefore, it should never be used in
new JavaScript code.
Name
Function.call( ): invoke a function as a method of an object — ECMAScript v3
Synopsis
function.call(thisobj,
args...)
Description
call( ) invokes the
specified function as if it were a method
of thisobj, passing it any arguments that
follow thisobj in the argument list. The
return value of call( ) is the
value returned by the function invocation. Within the body of the
function, the this keyword refers
to the thisobj object, or to the global
object if thisobj is null.
Use Function.apply( )
instead if you want to specify the arguments to pass to the function
in an array.
Name
Function.caller: the function that called this one — JavaScript 1.0; deprecated by ECMAScript
Description
In early versions of JavaScript, the caller property of a Function object is a
reference to the function that invoked the current one. If the
function is invoked from the top level of a JavaScript program,
caller is null. This property may be used only from
within the function (i.e., the caller property is only defined for a
function while that function is executing).
Function.caller is not part
of the ECMAScript standard and is not required in conforming
implementations. It should not be used.
Name
Function.length: the number of declared arguments — ECMAScript v1
Description
The length property of a
function specifies the number of named arguments declared when the
function was defined. The function may actually be invoked with more
than or fewer than this number of arguments. Don't confuse this
property of a Function object with the length property of the Arguments object,
which specifies the number of arguments actually passed to the
function. See Arguments.length
for an example.
Name
Function.prototype: the prototype for a class of objects — ECMAScript v1
Description
The prototype property is
used when a function is used as a constructor. It refers to an
object that serves as the prototype for an entire class of objects.
Any object created by the constructor inherits all properties of the
object referred to by the prototype property.
See Chapter 9, Classes, Constructors, and Prototypes for a full discussion of
constructor functions, the prototype property, and the definition of
classes in JavaScript.
Name
Function.toString( ): convert a function to a string — ECMAScript v1
Description
The toString( ) method of
the Function object converts a function to a string in an
implementation-dependent way. In most implementations, such as the
implementations in Firefox and IE, this method returns a string of
valid JavaScript code—code that includes the function keyword, argument list, the
complete body of the function, and so on. In these implementations,
the output of this toString( )
method is valid input for the global eval(
) function. This behavior is not required by the
specification, however, and should not be relied upon.
Name
getClass( ): return the JavaClass of a JavaObject — LiveConnect
Description
getClass( ) is a function
that takes a JavaObject object (javaobj)
as an argument. It returns the JavaClass object of that JavaObject.
That is, it returns the JavaClass object that represents the Java
class of the Java object represented by the specified
JavaObject.
Usage
Don't confuse the JavaScript getClass( ) function with the
getClass method of all Java objects. Similarly,
don't confuse the JavaScript JavaClass object with the Java
java.lang.Class class.
Consider the Java Rectangle object created with the following line:
var r = new java.awt.Rectangle( );
r is a JavaScript variable
that holds a JavaObject object. Calling the JavaScript function
getClass( ) returns a JavaClass
object that represents the java.awt.Rectangle
class:
var c = getClass(r);
You can see this by comparing this JavaClass object to
java.awt.Rectangle:
if (c == java.awt.Rectangle) ...
The Java getClass( ) method
is invoked differently and performs an entirely different
function:
c = r.getClass( );
After executing this line of code, c is a JavaObject that represents a
java.lang.Class object. This
java.lang.Class object is a Java
object that is a Java representation of the
java.awt.Rectangle class. See your Java
documentation for details on what you can do with the
java.lang.Class class.
To summarize, you can see that the following expression always
evaluates to true for any
JavaObject o:
(getClass(o.getClass( )) == java.lang.Class)
See Also
JavaArray, JavaClass, JavaObject, JavaPackage; Chapter 12, Scripting Java, Chapter 23, Scripting Java Applets and Flash Movies
Name
Global: the global object — ECMAScript v1: Object → Global
Global Properties
The global object is not a class, so the following global
properties have individual reference entries under their own
names. That is, you can find details on the undefined property listed under the name
undefined, not under Global.undefined. Note that all top-level
variables are also properties of the global object:
-
Infinity A numeric value that represents positive infinity.
-
java A JavaPackage that represents the java.* package hierarchy
-
NaN The not-a-number value.
-
Packages The root JavaPackage object.
-
undefined The
undefinedvalue.
Global Functions
The global object is an object, not a class. The global
functions listed here are not methods of any object, and their
reference entries appear under the function name. For example,
you'll find details on the parseInt(
) function under parseInt(
), not Global.parseInt(
):
-
decodeURI( ) Decodes a string escaped with
encodeURI( ).-
decodeURIComponent( ) Decodes a string escaped with
encodeURIComponent( ).-
encodeURI Encodes a URI by escaping certain characters.
-
encodeURIComponent Encodes a URI component by escaping certain characters.
-
escape( ) Encodes a string by replacing certain characters with escape sequences.
-
eval( ) Evaluates a string of JavaScript code and returns the result.
-
getClass( ) Returns the JavaClass of a JavaObject
-
isFinite( ) Tests whether a value is a finite number.
-
isNaN( ) Tests whether a value is the not-a-number value.
-
parseFloat( ) Parses a number from a string.
-
parseInt( ) Parses an integer from a string.
-
unescape( ) Decodes a string encoded with
escape( ).
Global Objects
In addition to the global properties and functions
listed earlier, the global object also defines properties that refer
to all the other predefined JavaScript objects. All these properties
are constructor functions that define classes except for Math, which is a reference to an object
that is not a constructor:
-
Array The
Array( )constructor.-
Boolean The
Boolean( )constructor.-
Date The
Date( )constructor.-
Error The
Error( )constructor.-
EvalError The
EvalError( )constructor.-
Function The
Function( )constructor.-
Math A reference to an object that defines mathematical functions.
-
Number The
Number( )constructor.-
Object The
Object( )constructor.-
RangeError The
RangeError( )constructor.-
ReferenceError The
ReferenceError( )constructor.-
RegExp The
RegExp( )constructor.-
String The
String( )constructor.-
SyntaxError The
SyntaxError( )constructor.-
TypeError The
TypeError( )constructor.-
URIError The
URIError( )constructor.
Description
The global object is a predefined object that serves
as a placeholder for the global properties and functions of
JavaScript. All other predefined objects, functions, and properties
are accessible through the global object. The global object is not a
property of any other object, so it does not have a name. (The title
of this reference page was chosen simply for organizational
convenience and does not indicate that the global object is named
"Global"). In top-level JavaScript code, you can refer to the global
object with the keyword this. It
is rarely necessary to refer to the global object in this way,
however, because the global object serves as the top of the scope
chain, which means that unqualified variable and function names are
looked up as properties of the object. When JavaScript code refers
to the parseInt( ) function, for
example, it is referring to the parseInt property of the global object.
The fact that the global object is the top of the scope chain also
means that all variables declared in top-level JavaScript code
become properties of the global object.
The global object is simply an object, not a class. There is
no Global( ) constructor, and
there is no way to instantiate a new global object.
When JavaScript is embedded in a particular environment, the
global object is usually given additional properties that are
specific to that environment. In fact, the type of the global object
is not specified by the ECMAScript standard, and an implementation
or embedding of JavaScript may use an object of any type as the
global object, as long as the object defines the basic properties
and functions listed here. For example, in JavaScript
implementations that allow the scripting of Java via LiveConnect or
related technologies, the global object is given the java and Packages properties and the getClass( ) method listed here. And in
client-side JavaScript, the global object is a Window object and
represents the web browser window within which the JavaScript code
is running.
Name
Infinity: a numeric property that represents infinity — ECMAScript v1
Description
Infinity is a global
property that contains the special numeric value representing
positive infinity. The Infinity
property is not enumerated by for/in loops and cannot be deleted with
the delete operator. Note that
Infinity is not a constant and
can be set to any other value, something that you should take care
not to do. (Number.POSITIVE_INFINITY is a constant,
however.)
Name
isNaN( ): check for not-a-number — ECMAScript v1
Description
isNaN( ) tests its
argument to determine whether it is the value NaN, which represents an illegal number (such as the
result of division by zero). This function is required because
comparing a NaN with any value,
including itself, always returns false, so it is not possible to test for
NaN with the == or === operators.
A common use of isNaN( ) is
to test the results of parseFloat(
) and parseInt( ) to
determine if they represent legal numbers. You can also use isNaN( ) to check for arithmetic errors,
such as division by zero.
Name
java: the JavaPackage for the java.* package hierarchy — LiveConnect
Description
In JavaScript implementations that include LiveConnect or
other technology for scripting Java, the global java
property is a JavaPackage object that represents the
java.* package hierarchy. The existence of this
property means that a JavaScript expression such as java.util refers to the Java package
java.util. For Java packages that do not fall
in the java.* hierarchy, see the global
Packages property.
Name
JavaArray: JavaScript representation of a Java array — LiveConnect
Synopsis
javaarray.length // The length of
the array
javaarray[index]
// Read or write an array element
Properties
-
length A read-only integer that specifies the number of elements in the Java array represented by the JavaArray object.
Description
The JavaArray object is a JavaScript representation of a Java
array that allows JavaScript code to read and write the elements of
the array using familiar JavaScript array syntax. In addition, the
JavaArray object has a length
field that specifies the number of elements in the Java
array.
When reading and writing values from array elements, data conversion between JavaScript and Java representations is automatically handled by the system. See Chapter 12, Scripting Java for full details.
Usage
Note that Java arrays differ from JavaScript arrays in a
couple of important aspects. First, Java arrays have a fixed length
that is specified when they are created. For this reason, the
JavaArray length field is
read-only. The second difference is that Java arrays are
typed (i.e., their elements must all be of the
same type of data). Attempting to set an array element to a value of
the wrong type results in a JavaScript error or exception.
Example
java.awt.Polygon is a
JavaClass object. You can create a JavaObject representing an
instance of the class like this:
p = new java.awt.Polygon( );
The object p has properties
xpoints and ypoints, which are JavaArray objects
representing Java arrays of integers. You can initialize the
contents of these arrays with JavaScript code like the
following:
for(var i = 0; i < p.xpoints.length; i++)
p.xpoints[i] = Math.round(Math.random( )*100);
for(var i = 0; i < p.ypoints.length; i++)
p.ypoints[i] = Math.round(Math.random( )*100);Name
JavaClass: JavaScript representation of a Java class — LiveConnect
Synopsis
javaclass.static_member// Read or write a static Java field or method newjavaclass(...) // Create a new Java object
Properties
Each JavaClass object contains properties that have the same
names as the public static fields and methods of the Java class it
represents. These properties allow you to read and write the static
fields of the class and invoke the static methods of the class. Each
JavaClass object has different properties; you can use a for/in loop to enumerate them for any
given JavaClass object.
Description
The JavaClass object is a JavaScript representation of a Java class. The properties of a JavaClass object represent the public static fields and methods (sometimes called class fields and class methods) of the represented class. Note that the JavaClass object does not have properties representing the instance fields of a Java class; individual instances of a Java class are represented by the JavaObject object.
The JavaClass object implements the LiveConnect functionality that allows JavaScript programs to read and write the static variables of Java classes using normal JavaScript syntax. It also provides the functionality that allows JavaScript to invoke the static methods of a Java class.
In addition to allowing JavaScript to read and write Java
variable and method values, the JavaClass object allows JavaScript
programs to create Java objects (represented by a JavaObject object)
by using the new keyword and
invoking the constructor method of a JavaClass.
The data conversion required for communication between JavaScript and Java through the JavaClass object is handled automatically by LiveConnect. See Chapter 12, Scripting Java for full details.
Usage
Bear in mind that Java is a typed language. This means that each of the fields of an object has a specific datatype that is set to values of only that type. Attempting to set a field to a value that is not of the correct type results in a JavaScript error or exception. Attempting to invoke a method with arguments of the wrong type also causes an error or exception.
Example
java.lang.System is a
JavaClass object that represents the
java.lang.System class in Java. You can read a
static field of this class with code like the following:
var java_console = java.lang.System.out;
You can invoke a static method of this class with a line like this one:
var version = java.lang.System.getProperty("java.version");Finally, the JavaClass object also allows you to create new Java objects:
var java_date = new java.lang.Date( );
Name
JavaObject: JavaScript representation of a Java object — LiveConnect
Properties
Each JavaObject object contains properties that have the same
names as the public instance fields and methods (but not the static
or class fields and methods) of the Java object it represents. These
properties allow you to read and write the value of public fields
and invoke the public methods. The properties of a given JavaObject
object obviously depend on the type of Java object it represents.
You can use the for/in loop to
enumerate the properties of any given JavaObject.
Description
The JavaObject object is a JavaScript representation of a Java object. The properties of a JavaObject object represent the public instance fields and public instance methods defined for the Java object. (The class or static fields and methods of the object are represented by the JavaClass object.)
The JavaObject object implements the LiveConnect functionality that allows JavaScript programs to read and write the public instance fields of a Java object using normal JavaScript syntax. It also provides the functionality that allows JavaScript to invoke the methods of a Java object. Data conversion between JavaScript and Java representations is handled automatically by LiveConnect. See Chapter 12, Scripting Java for full details.
Usage
Bear in mind that Java is a typed
language. This means that each field of an object has a specific
datatype, and you can set it only to values of that type. For
example, the width field of a
java.awt.Rectangle object is an
integer field, and attempting to set it to a string causes a
JavaScript error or exception.
Example
java.awt.Rectangle is a
JavaClass that represents the
java.awt.Rectangle class. You can create a
JavaObject that represents an instance of this class like
this:
var r = new java.awt.Rectangle(0,0,4,5);
You can then read the public instance variables of this
JavaObject r with code like
this:
var perimeter = 2*r.width + 2*r.height;
You can also set the value of public instance variables of
r using JavaScript syntax:
r.width = perimeter/4; r.height = perimeter/4;
Name
JavaPackage: JavaScript representation of a Java package — LiveConnect
Synopsis
package.package_name// Refers to another JavaPackagepackage.class_name// Refers to a JavaClass object
Properties
The properties of a JavaPackage object are the names of the
JavaPackage objects and JavaClass objects that it contains. These
properties are different for each individual JavaPackage. Note that
it is not possible to use the JavaScript for/in loop to iterate over the list of
property names of a Package object. Consult a Java reference manual
to determine the packages and classes contained within any given
package.
Description
The JavaPackage object is a JavaScript representation of a Java package. A package in Java is a collection of related classes. In JavaScript, a JavaPackage can contain classes (represented by the JavaClass object) and other JavaPackage objects.
The global object has a JavaPackage property named java that represents the
java.* package hierarchy. This JavaPackage
object defines properties that refer to other JavaPackage objects.
For example, java.lang and
java.net refer to the
java.lang and http://java.net
packages. The java.awt
JavaPackage contains properties named Frame and Button, which are references to JavaClass
objects and represent the classes
java.awt.Frame and
java.awt.Button.
The global object also defines a property named Packages, which is the root JavaPackage
whose properties refer to the roots of all known package
hierarchies. For example, the expression Packages.javax.swing refers to the Java
package javax.swing.
It is not possible to use the for/in loop to determine the names of the
packages and classes contained within a JavaPackage. You must have
this information in advance. You can find it in any Java reference
manual or by examining the Java class hierarchy.
See Chapter 12, Scripting Java for further details on working with Java packages, classes, and objects.
Name
Math: mathematical functions and constants — ECMAScript v1
Constants
-
Math.E The constant e, the base of the natural logarithm.
-
Math.LN10 The natural logarithm of 10.
-
Math.LN2 The natural logarithm of 2.
-
Math.LOG10E The base-10 logarithm of e.
-
Math.LOG2E The base-2 logarithm of e.
-
Math.PI The constant π.
-
Math.SQRT1_2 The number 1 divided by the square root of 2.
-
Math.SQRT2 The square root of 2.
Static Functions
-
Math.abs( ) Computes an absolute value.
-
Math.acos( ) Computes an arccosine.
-
Math.asin( ) Computes an arcsine.
-
Math.atan( ) Computes an arctangent.
-
Math.atan2( ) Computes the angle from the X axis to a point.
-
Math.ceil( ) Rounds a number up.
-
Math.cos( ) Computes a cosine.
-
Math.exp( ) Computes a power of e.
-
Math.floor( ) Rounds a number down.
-
Math.log( ) Computes a natural logarithm.
-
Math.max( ) Returns the larger of two numbers.
-
Math.min( ) Returns the smaller of two numbers.
-
Math.pow( ) Computes x y
-
Math.random( ) Computes a random number.
-
Math.round( ) Rounds to the nearest integer.
-
Math.sin( ) Computes a sine.
-
Math.sqrt( ) Computes a square root.
-
Math.tan( ) Computes a tangent.
Description
Math is an object that defines properties that refer to useful mathematical functions and constants. These functions and constants are invoked with syntax like this:
y = Math.sin(x); area = radius * radius * Math.PI;
Math is not a class of objects as Date and String are. There
is no Math( ) constructor, and
functions like Math.sin( ) are
simply functions, not methods that operate on an object.
Name
Math.atan2( ): compute the angle from the X axis to a point — ECMAScript v1
Description
The Math.atan2( ) function
computes the arc tangent of the ratio
y/x. The
y argument can be considered the Y
coordinate (or "rise") of a point, and the
x argument can be considered the X
coordinate (or "run") of the point. Note the unusual order of the
arguments to this function: the Y coordinate is passed before the X
coordinate.
Name
Math.ceil( ): round a number up — ECMAScript v1
Description
Math.ceil( ) computes the
ceiling function—i.e., it returns the closest integer value that is
greater than or equal to the function argument. Math.ceil( ) differs from Math.round( ) in that it always rounds up,
rather than rounding up or down to the closest integer. Also note
that Math.ceil( ) does not round
negative numbers to larger negative numbers; it rounds them up
toward zero.
Name
Math.floor( ): round a number down — ECMAScript v1
Description
Math.floor( ) computes the
floor function; in other words, it returns the nearest integer value
that is less than or equal to the function argument.
Math.floor( ) rounds a
floating-point value down to the closest integer. This behavior
differs from that of Math.round(
), which rounds up or down to the nearest integer. Also
note that Math.floor( ) rounds
negative numbers down (i.e., to be more negative), not up (i.e.,
closer to zero).
Name
Math.log( ): compute a natural logarithm — ECMAScript v1
Description
Math.log( ) computes
log e
x, the natural logarithm of its argument. The
argument must be greater than zero.
You can compute the base-10 and base-2 logarithms of a number with these formulas:
log10x = log10e · logex log2x = log2e · logex
These formulas translate into the following JavaScript functions:
function log10(x) { return Math.LOG10E * Math.log(x); }
function log2(x) { return Math.LOG2E * Math.log(x); }Name
Math.max( ): return the largest argument — ECMAScript v1; enhanced in ECMAScript v3
Name
Math.min( ): return the smallest argument — ECMAScript v1; enhanced in ECMAScript v3
Name
Math.pow( ): compute 'x'y — ECMAScript v1
Description
Math.pow( ) computes
x to the power of
y. Any values of
x and y may be
passed to Math.pow( ). However,
if the result is an imaginary or complex number, Math.pow( ) returns NaN. In practice, this means that if
x is negative,
y should be a positive or negative
integer. Also, bear in mind that large exponents can easily cause
floating-point overflow and return a value of Infinity.
Name
NaN: the not-a-number property — ECMAScript v1
Description
NaN is a global property
that refers to the special numeric not-a-number value. The NaN property is not enumerated by for/in loops and cannot be deleted with
the delete operator. Note that
NaN is not a constant and can be
set to any other value, something that you should take care not to
do.
To determine if a value is not a number, use isNaN( ), because NaN always compares as nonequal to any
other value, including itself!
Name
Number: support for numbers — ECMAScript v1: Object → Number
Constants
-
Number.MAX_VALUE The largest representable number.
-
Number.MIN_VALUE The smallest representable number.
-
Number.NaN Not-a-number value.
-
Number.NEGATIVE_INFINITY Negative infinite value; returned on overflow.
-
Number.POSITIVE_INFINITY Infinite value; returned on overflow.
Methods
-
toString( ) Converts a number to a string using a specified radix (base).
-
toLocaleString( ) Converts a number to a string using local number-formatting conventions.
-
toFixed( ) Converts a number to a string that contains a specified number of digits after the decimal place.
-
toExponential( ) Converts a number to a string using exponential notation with the specified number of digits after the decimal place.
-
toPrecision( ) Converts a number to a string using the specified number of significant digits. Uses exponential or fixed-point notation depending on the size of the number and the number of significant digits specified.
-
valueOf( ) Returns the primitive numeric value of a Number object.
Description
Numbers are a basic, primitive datatype in JavaScript.
JavaScript also supports the Number object, which is a wrapper
object around a primitive numeric value. JavaScript automatically
converts between the primitive and object forms as necessary. You
can explicitly create a Number object with the Number( ) constructor, although there is
rarely any need to do so.
The Number( ) constructor
can also be used without the new
operator, as a conversion function. When invoked in this way, it
attempts to convert its argument to a number and returns the
primitive numeric value (or NaN)
that results from the conversion.
The Number( ) constructor
is also used as a placeholder for five useful numeric constants: the
largest and smallest representable numbers, positive and negative
infinity, and the special NaN
value. Note that these values are properties of the Number( ) constructor function itself, not
of individual number objects. For example, you can use the MAX_VALUE property as follows:
var biggest = Number.MAX_VALUE
but not like this:
var n = new Number(2); var biggest = n.MAX_VALUE
By contrast, the toString(
) and other methods of the Number object are methods of
each Number object, not of the Number(
) constructor function. As noted earlier, JavaScript
automatically converts from primitive numeric values to Number
objects whenever necessary. This means that you can use the Number
methods with primitive numeric values as well as with Number
objects.
var value = 1234; var binary_value = n.toString(2);
Name
Number.NaN: the special not-a-number value — ECMAScript v1
Description
Number.NaN is a special
value that indicates that the result of some mathematical operation
(such as taking the square root of a negative number) is not a
number. parseInt( ) and parseFloat( ) return this value when they
cannot parse the specified string, and you might use Number.NaN in a similar way to indicate an
error condition for some function that normally returns a valid
number.
JavaScript prints the Number.NaN value as NaN. Note that the NaN value always compares as unequal to
any other number, including NaN
itself. Thus, you cannot check for the not-a-number value by
comparing to Number.NaN; use the
isNaN( ) function instead. In
ECMAScript v1 and later, you can also use the predefined global
property NaN instead of Number.NaN.
Name
Number.NEGATIVE_INFINITY: negative infinity — ECMAScript v1
Description
Number.NEGATIVE_INFINITY is
a special numeric value that is returned when an arithmetic
operation or mathematical function generates a negative value
greater than the largest representable number in JavaScript (i.e.,
more negative than -Number.MAX_VALUE).
JavaScript displays the NEGATIVE_INFINITY value as -Infinity. This value behaves
mathematically like infinity; for example, anything multiplied by
infinity is infinity, and anything divided by infinity is zero. In
ECMAScript v1 and later, you can also use -Infinity instead of Number.NEGATIVE_INFINITY.
Name
Number.POSITIVE_INFINITY: infinity — ECMAScript v1
Description
Number.POSITIVE_INFINITY is
a special numeric value returned when an arithmetic operation or
mathematical function overflows or generates a value greater than
the largest representable number in JavaScript (i.e., greater than
Number.MAX_VALUE). Note that when
numbers "underflow," or become less than Number.MIN_VALUE, JavaScript converts them
to zero.
JavaScript displays the POSITIVE_INFINITY value as Infinity. This value behaves
mathematically like infinity; for example, anything multiplied by
infinity is infinity, and anything divided by infinity is zero. In
ECMAScript v1 and later, you can also use the predefined global
property Infinity instead of
Number.POSITIVE_INFINITY.
Name
Number.toExponential( ): format a number using exponential notation — ECMAScript v3
Synopsis
number.toExponential(digits)
Arguments
-
digits The number of digits that appears after the decimal point. This may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, as many digits as necessary are used.
Name
Number.toFixed( ): format a number using fixed-point notation — ECMAScript v3
Synopsis
number.toFixed(digits)
Arguments
-
digits The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Returns
A string representation of number
that does not use exponential notation and has exactly
digits digits after the decimal place.
The number is rounded if necessary, and the fractional part is
padded with zeros if necessary so that it has the specified
length. If number is greater than
1e+21, this method simply calls Number.toString( ) and returns a string
in exponential notation.
Name
Number.toLocaleString( ): convert a number to a locally formatted string — ECMAScript v3
Name
Number.toPrecision( ): format the significant digits of a number — ECMAScript v3
Synopsis
Arguments
-
precision The number of significant digits to appear in the returned string. This may be a value between 1 and 21, inclusive. Implementations are allowed to optionally support larger and smaller values of
precision. If this argument is omitted, thetoString( )method is used instead to convert the number to a base-10 value.
Returns
A string representation of number
that contains precision significant
digits. If precision is large enough to
include all the digits of the integer part of
number, the returned string uses
fixed-point notation. Otherwise, exponential notation is used with
one digit before the decimal place and
precision−1 digits after the decimal
place. The number is rounded or padded with zeros as
necessary.
Name
Number.toString( ): convert a number to a string — ECMAScript v1: Overrides Object.toString( )
Synopsis
number.toString(radix)
Arguments
-
radix An optional argument that specifies the radix, or base, between 2 and 36, in which the number should be represented. If omitted, base 10 is used. Note, however, that the ECMAScript specification allows an implementation to return any value if this argument is specified as any value other than 10.
Description
The toString( ) method of
the Number object converts a number to a string. When the
radix argument is omitted or is specified
as 10, the number is converted to a base-10 string. Although the
ECMAScript specification does not require implementations to honor
any other values for radix, all implementations in common use accept
values between 2 and 36.
Name
Number.valueOf( ): return the primitive number value — ECMAScript v1: Overrides Object.valueOf( )
Name
Object: a superclass that contains features of all JavaScript objects — ECMAScript v1
Constructor
new Object( )
new Object(value)Arguments
-
value This optional argument specifies a primitive JavaScript value—a number, boolean, or string—that is to be converted to a Number, Boolean, or String object.
Returns
If no value argument is passed,
this constructor returns a newly created Object instance. If a
primitive value argument is specified,
the constructor creates and returns a Number, Boolean, or String
object wrapper for the primitive value. When the Object( ) constructor is called as a
function, without the new
operator, it behaves just as it does when used with the new operator.
Properties
-
constructor A reference to the JavaScript function that was the constructor for the object.
Methods
-
hasOwnProperty( ) Checks whether an object has a locally defined (noninherited) property with a specified name.
-
isPrototypeOf( ) Checks whether this object is the prototype object of a specified object.
-
propertyIsEnumerable( ) Checks whether a named property exists and would be enumerated by a
for/inloop.-
toLocaleString( ) Returns a localized string representation of the object. The default implementation of this method simply calls
toString( ), but subclasses may override it to provide localization.-
toString( ) Returns a string representation of the object. The implementation of this method provided by the Object class is quite generic and does not provide much useful information. Subclasses of Object typically override this method by defining their own
toString( )method, which produces more useful output.-
valueOf( ) Returns the primitive value of the object, if any. For objects of type Object, this method simply returns the object itself. Subclasses of Object, such as Number and Boolean, override this method to return the primitive value associated with the object.
Description
The Object class is a built-in datatype of the JavaScript language. It serves as the superclass for all other JavaScript objects; therefore, methods and behavior of the Object class are inherited by all other objects. The basic behavior of objects in JavaScript is explained in Chapter 7, Objects and Arrays.
In addition to the Object(
) constructor shown above, objects can also be created and
initialized using the Object literal syntax described in Chapter 7, Objects and Arrays.
See Also
Array, Boolean, Function, Function.prototype, Number, String; Chapter 7, Objects and Arrays
Name
Object.constructor: an object's constructor function — ECMAScript v1
Description
The constructor property of
any object is a reference to the function that was used as the
constructor for that object. For example, if you create an array
a with the Array( ) constructor, a.constructor is an Array:
a = new Array(1,2,3); // Create an object a.constructor == Array // Evaluates to true
One common use of the constructor property is to determine the
type of unknown objects. Given an unknown value, you can use the
typeof operator to determine
whether it is a primitive value or an object. If it is an object,
you can use the constructor
property to determine what type of object it is. For example, the
following function determines whether a given value is an
array:
function isArray(x) {
return ((typeof x == "object") && (x.constructor == Array));
}Note, however, that while this technique works for the objects
built into core JavaScript, it is not guaranteed to work with host
objects such as the Window object of client-side JavaScript. The
default implementation of the Object.toString( ) method provides another
way to determine the type of an unknown object.
Name
Object.hasOwnProperty( ): check whether a property is inherited — ECMAScript v3
Description
As explained in Chapter 9, Classes, Constructors, and Prototypes, JavaScript
objects may have properties of their own, and they may also inherit
properties from their prototype object. The hasOwnProperty( ) method provides a way to
distinguish between inherited properties and noninherited local
properties.
Example
var o = new Object( ); // Create an object
o.x = 3.14; // Define a noninherited local property
o.hasOwnProperty("x"); // Returns true: x is a local property of o
o.hasOwnProperty("y"); // Returns false: o doesn't have a property y
o.hasOwnProperty("toString"); // Returns false: toString property is inheritedSee Also
Function.prototype,
Object.propertyIsEnumerable( );
Chapter 9, Classes, Constructors, and Prototypes
Name
Object.isPrototypeOf( ): is one object the prototype of another? — ECMAScript v3
Description
As explained in Chapter 9, Classes, Constructors, and Prototypes, JavaScript
objects inherit properties from their prototype object. The
prototype of an object is referred to by the prototype property of the constructor
function that creates and initializes the object. The isPrototypeOf( ) method provides a way to
determine if one object is the prototype of another. This technique
can be used to determine the class of an object.
Example
var o = new Object( ); // Create an object Object.prototype.isPrototypeOf(o) // true: o is an object Function.prototype.isPrototypeOf(o.toString); // true: toString is a function Array.prototype.isPrototypeOf([1,2,3]); // true: [1,2,3] is an array // Here is a way to perform a similar test (o.constructor == Object); // true: o was created with Object( ) constructor (o.toString.constructor == Function); // true: o.toString is a function // Prototype objects themselves have prototypes. The following call // returns true, showing that function objects inherit properties // from Function.prototype and also from Object.prototype. Object.prototype.isPrototypeOf(Function.prototype);
Name
Object.propertyIsEnumerable( ): will property be seen by a for/in loop? — ECMAScript v3
Description
The for/in statement loops
through the enumerable properties of an object. Not all properties
of an object are enumerable, however: properties added to an object
by JavaScript code are enumerable, but the predefined properties
(such as methods) of built-in objects are not usually enumerable.
The propertyIsEnumerable( )
method provides a way to distinguish between enumerable and
nonenumerable properties. Note, however, that the ECMAScript
specification states that propertyIsEnumerable( ) does not examine
the prototype chain, which means it works only for local properties
of an object and does not provide any way to test the enumerability
of inherited properties.
Example
var o = new Object( ); // Create an object
o.x = 3.14; // Define a property
o.propertyIsEnumerable("x"); // true: property x is local and enumerable
o.propertyIsEnumerable("y"); // false: o doesn't have a property y
o.propertyIsEnumerable("toString"); // false: toString property is inherited
Object.prototype.propertyIsEnumerable("toString"); // false: nonenumerableName
Object.toLocaleString( ): return an object's localized string representation — ECMAScript v3
Description
This method is intended to return a string representation of
the object, localized as appropriate for the current locale. The
default toLocaleString( ) method
provided by the Object class simply calls the toString( ) method and returns the
nonlocalized string that it returns. Note, however, that other
classes, including Array, Date, and Number, define their own
versions of this method to perform localized string conversions.
When defining your own classes, you may want to override this method
as well.
Name
Object.toString( ): define an object's string representation — ECMAScript v1
Description
The toString( ) method is
not one you often call explicitly in your JavaScript programs.
Instead, you define this method in your objects, and the system
calls it whenever it needs to convert your object to a
string.
The JavaScript system invokes the toString( ) method to convert an object to
a string whenever the object is used in a string context. For
example, an object is converted to a string when it is passed to a
function that expects a string argument:
alert(my_object);
Similarly, objects are converted to strings when they are
concatenated to strings with the + operator:
var msg = 'My object is: ' + my_object;
The toString( ) method is
invoked without arguments and should return a string. To be useful,
the string you return should be based, in some way, on the value of
the object for which the method was invoked.
When you define a custom class in JavaScript, it is good
practice to define a toString( )
method for the class. If you do not, the object inherits the default
toString( ) method from the
Object class. This default method returns a string of the
form:
[objectclass]where class is the class of the
object: a value such as "Object", "String", "Number", "Function",
"Window", "Document", and so on. This behavior of the default
toString( ) method is
occasionally useful to determine the type or class of an unknown
object. Because most objects have a custom version of toString( ), however, you must explicitly
invoke the Object.toString( )
method on an object o with code
like this:
Object.prototype.toString.apply(o);
Note that this technique for identifying unknown objects works
only for built-in objects. If you define your own object class, it
will have a class of "Object". In this
case, you can use the Object.constructor property to obtain more
information about the object.
The toString( ) method can
be quite useful when you are debugging JavaScript programs; it
allows you to print objects and see their value. For this reason
alone, it is a good idea to define a toString( ) method for every object class
you create.
Although the toString( )
method is usually invoked automatically by the system, there are
times when you may invoke it yourself. For example, you might want
to do an explicit conversion of an object to a string in a situation
where JavaScript does not do it automatically for you:
y = Math.sqrt(x); // Compute a number ystr = y.toString( ); // Convert it to a string
Note in this example that numbers have a built-in toString( ) method you can use to force a
conversion.
In other circumstances, you can choose to use a toString( ) call even in a context where
JavaScript does the conversion automatically. Using toString( ) explicitly can help to make
your code clearer:
alert(my_obj.toString( ));
Name
Object.valueOf( ): the primitive value of the specified object — ECMAScript v1
Description
The valueOf( ) method of an
object returns the primitive value associated with that object, if
there is one. For objects of type Object, there is no primitive
value, and this method simply returns the object itself.
For objects of type Number, however, valueOf( ) returns the primitive numeric
value represented by the object. Similarly, it returns the primitive
boolean value associated with a Boolean object and the string
associated with a String object.
It is rarely necessary to invoke the valueOf( ) method yourself. JavaScript
does this automatically whenever an object is used where a primitive
value is expected. In fact, because of this automatic invocation of
the valueOf( ) method, it is
difficult to even distinguish between primitive values and their
corresponding objects. The typeof
operator shows you the difference between strings and String objects
for example, but in practical terms, you can use them equivalently
in your JavaScript code.
The valueOf( ) methods of
the Number, Boolean, and String objects convert these wrapper
objects to the primitive values they represent. The Object( ) constructor performs the
opposite operation when invoked with a number, boolean, or string
argument: it wraps the primitive value in an appropriate object
wrapper. JavaScript performs this primitive-to-object conversion for
you in almost all circumstances, so it is rarely necessary to invoke
the Object( ) constructor in this
way.
In some circumstances, you may want to define a custom
valueOf( ) method for your own
objects. For example, you might define a JavaScript object type to
represent complex numbers (a real number plus an imaginary number).
As part of this object type, you would probably define methods for
performing complex addition, multiplication, and so on (see Example 9-2, “A complex number class”). But you might also want to treat
your complex numbers like ordinary real numbers by discarding the
imaginary part. To achieve this, you might do something like the
following:
Complex.prototype.valueOf = new Function("return this.real");With this valueOf( ) method
defined for your Complex object type, you can, for example, pass one
of your complex number objects to Math.sqrt( ), which computes the square
root of the real portion of the complex number.
Name
Packages: the root JavaPackage — LiveConnect
Description
In JavaScript implementations that include LiveConnect or
other technology for scripting Java, the global Packages property is a JavaPackage object
whose properties are all the package roots known to the Java
interpreter. For example, Packages.javax.swing refers to the Java
package javax.swing. The global property
java is a shortcut for Packages.java.
Name
parseFloat( ): convert a string to a number — ECMAScript v1
Description
parseFloat( ) parses and
returns the first number that occurs in
s. Parsing stops, and the value is
returned, when parseFloat( )
encounters a character in s that is not a
valid part of the number. If s does not
begin with a number that parseFloat(
) can parse, the function returns the not-a-number value
NaN. Test for this return value
with the isNaN( ) function. If
you want to parse only the integer portion of a number, use parseInt( ) instead of parseFloat( ).
Name
parseInt( ): convert a string to an integer — ECMAScript v1
Synopsis
parseInt(s)parseInt(s,
radix)
Arguments
-
s The string to be parsed.
-
radix An optional integer argument that represents the radix (i.e., base) of the number to be parsed. If this argument is omitted or is 0, the number is parsed in base 10—or in base 16 if it begins with 0x or 0X. If this argument is less than 2 or greater than 36,
parseInt( )returnsNaN.
Description
parseInt( ) parses and
returns the first number (with an optional leading minus sign) that
occurs in s. Parsing stops, and the value
is returned, when parseInt( )
encounters a character in s that is not a
valid digit for the specified radix. If
s does not begin with a number that
parseInt( ) can parse, the
function returns the not-a-number value NaN. Use the isNaN( ) function to test for this return
value.
The radix argument specifies the
base of the number to be parsed. Specifying 10 makes parseInt( ) parse a decimal number. The
value 8 specifies that an octal number (using digits 0 through 7) is
to be parsed. The value 16 specifies a hexadecimal value, using
digits 0 through 9 and letters A through F.
radix can be any value between 2 and
36.
If radix is 0 or is not specified,
parseInt( ) tries to determine
the radix of the number from s. If
s begins (after an optional minus sign)
with 0x, parseInt( ) parses the remainder of
s as a hexadecimal number. If
s begins with a 0, the ECMAScript v3
standard allows an implementation of parseInt( ) to interpret the following
characters as an octal number or as a decimal number. Otherwise, if
s begins with a digit from 1 through 9,
parseInt( ) parses it as a
decimal number.
Example
parseInt("19", 10); // Returns 19 (10 + 9)
parseInt("11", 2); // Returns 3 (2 + 1)
parseInt("17", 8); // Returns 15 (8 + 7)
parseInt("1f", 16); // Returns 31 (16 + 15)
parseInt("10"); // Returns 10
parseInt("0x10"); // Returns 16
parseInt("010"); // Ambiguous: returns 10 or 8Bugs
When no radix is specified,
ECMAScript v3 allows an implementation to parse a string that begins
with 0 (but not 0x or 0X) as an octal or as a decimal number. To
avoid this ambiguity, you should explicitly specify a radix or leave
the radix unspecified only when you are sure that all numbers to be
parsed will be decimal numbers, or hexadecimal numbers with the 0x
or 0X prefix.
Name
RangeError: thrown when a number is out of its legal range — ECMAScript v3: Object → Error → RangeError
Constructor
new RangeError( )
new RangeError(message)Returns
A newly constructed RangeError object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the RangeError(
) constructor is called as a function, without the
new operator, it behaves just
as it would when called with the new operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string. See
Error.messagefor details.-
name A string that specifies the type of the exception. All RangeError objects inherit the value "RangeError" for this property.
Name
ReferenceError: thrown when reading a variable that does not exist — ECMAScript v3: Object → Error → ReferenceError
Constructor
new ReferenceError( )
new ReferenceError(message)Returns
A newly constructed ReferenceError object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the ReferenceError(
) constructor is called as a function, without the
new operator, it behaves just
as it would with the new
operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string. See
Error.messagefor details.-
name A string that specifies the type of the exception. All ReferenceError objects inherit the value "ReferenceError" for this property.
Name
RegExp: regular expressions for pattern matching — ECMAScript v3: Object → RegExp
Constructor
new
RegExp(
pattern,
attributes)
Arguments
-
pattern A string that specifies the pattern of the regular expression or another regular expression.
-
attributes An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively. The "m" attribute is not available prior to ECMAScript standardization. If the
patternargument is a regular expression instead of a string, this argument must be omitted.
Returns
A new RegExp object, with
the specified pattern and flags. If the
pattern argument is a regular
expression rather than a string, the RegExp( ) constructor creates a new
RegExp object using the same pattern and flags as the specified
RegExp. If RegExp( ) is called
as a function without the new
operator, it behaves just as it would with the new operator, except when
pattern is a regular expression; in
that case, it simply returns pattern
instead of creating a new RegExp object.
Instance Properties
-
global Whether the RegExp has the "g" attribute.
-
ignoreCase Whether the RegExp has the "i" attribute.
-
lastIndex The character position of the last match; used for finding multiple matches in a string.
-
multiline Whether the RegExp has the "m" attribute.
-
source The source text of the regular expression.
Methods
-
exec( ) Performs powerful, general-purpose pattern matching.
-
test( ) Tests whether a string contains a pattern.
Description
The RegExp object represents a regular expression, a powerful tool for performing pattern matching on strings. See Chapter 11, Pattern Matching with Regular Expressions for complete details on regular-expression syntax and use.
Name
RegExp.exec( ): general-purpose pattern matching — ECMAScript v3
Synopsis
regexp.exec(string)
Description
exec( ) is the most
powerful of all the RegExp and String pattern-matching methods. It
is a general-purpose method that is somewhat more complex to use
than RegExp.test( ), String.search( ), String.replace( ), and String.match( ).
exec( ) searches
string for text that matches
regexp. If it finds a match, it returns
an array of results; otherwise, it returns null. Element 0 of the returned array is
the matched text. Element 1 is the text that matched the first
parenthesized subexpression, if any, within
regexp. Element 2 contains the text that
matched the second subexpression, and so on. The array length property specifies the number of
elements in the array, as usual. In addition to the array elements
and the length property, the
value returned by exec( ) also
has two other properties. The index property specifies the character
position of the first character of the matched text. The input property refers to
string. This returned array is the same
as the array that is returned by the String.match( ) method, when invoked on a
nonglobal RegExp object.
When exec( ) is invoked on
a nonglobal pattern, it performs the search and returns the result
described earlier. When regexp is a
global regular expression, however, exec(
) behaves in a slightly more complex way. It begins
searching string at the character
position specified by the lastIndex property of
regexp. When it finds a match, it sets
lastIndex to the position of the
first character after the match. This means that you can invoke
exec( ) repeatedly in order to
loop through all matches in a string. When exec( ) cannot find any more matches, it
returns null and resets lastIndex to zero. If you begin searching
a new string immediately after successfully finding a match in
another string, you must be careful to manually reset lastIndex to zero.
Note that exec( ) always
includes full details of every match in the array it returns,
whether or not regexp is a global
pattern. This is where exec( )
differs from String.match( ),
which returns much less information when used with global patterns.
Calling the exec( ) method
repeatedly in a loop is the only way to obtain complete
pattern-matching information for a global pattern.
Example
You can use exec( )
in a loop to find all matches within a string. For example:
var pattern = /\bJava\w*\b/g;
var text = "JavaScript is more fun than Java or JavaBeans!";
var result;
while((result = pattern.exec(text)) != null) {
alert("Matched '" + result[0] +
"' at position " + result.index +
" next search begins at position " + pattern.lastIndex);
}See Also
RegExp.lastIndex, RegExp.test( ), String.match( ), String.replace( ), String.search( ); Chapter 11, Pattern Matching with Regular Expressions
Name
RegExp.lastIndex: the starting position of the next match — ECMAScript v3
Description
lastIndex is a read/write
property of RegExp objects. For regular expressions with the "g"
attribute set, it contains an integer that specifies the character
position immediately following the last match found by the RegExp.exec( ) and RegExp.test( ) methods. These methods use
this property as the starting point for the next search they
conduct. This allows you to call those methods repeatedly, to loop
through all matches in a string. Note that lastIndex is not used by RegExp objects
that do not have the "g" attribute set and do not represent global
patterns.
This property is read/write, so you can set it at any time to
specify where in the target string the next search should begin.
exec( ) and test( ) automatically reset lastIndex to 0 when they fail to find a
match (or another match). If you begin to search a new string after
a successful match of some other string, you have to explicitly set
this property to 0.
Name
RegExp.test( ): test whether a string matches a pattern — ECMAScript v3
Description
test( ) tests
string to see if it contains text that
matches regexp. If so, it returns
true; otherwise, it returns
false. Calling the test( ) method of a RegExp
r and passing it the string
s is equivalent to the following
expression:
(r.exec(s) != null)
Example
var pattern = /java/i;
pattern.test("JavaScript"); // Returns true
pattern.test("ECMAScript"); // Returns falseSee Also
RegExp.exec( ), RegExp.lastIndex, String.match( ), String.replace( ), String.substring( ); Chapter 11, Pattern Matching with Regular Expressions
Name
RegExp.toString( ): convert a regular expression to a string — ECMAScript v3: Overrides Object.toString( )
Description
The RegExp.toString( )
method returns a string representation of a regular expression in
the form of a regular-expression literal.
Note that implementations are not required to add escape
sequences to ensure that the returned string is a legal
regular-expression literal. Consider the regular expression created
by the expression new
RegExp("/","g"). An implementation of RegExp.toString( ) could return ///g for this regular expression; it could
also add an escape sequence and return /\//g.
Name
String: support for strings — ECMAScript v1: Object → String
Methods
-
charAt( ) Extracts the character at a given position from a string.
-
charCodeAt( ) Returns the encoding of the character at a given position in a string.
-
concat( ) Concatenates one or more values to a string.
-
indexOf( ) Searches the string for a character or substring.
-
lastIndexOf( ) Searches the string backward for a character or substring.
-
localeCompare( ) Compares strings using locale-specific ordering.
-
match( ) Performs pattern matching with a regular expression.
-
replace( ) Performs a search-and-replace operation with a regular expression.
-
search( ) Searches a string for a substring that matches a regular expression.
-
slice( ) Returns a slice or substring of a string.
-
split( ) Splits a string into an array of strings, breaking at a specified delimiter string or regular expression.
-
substr( ) Extracts a substring of a string; a variant of
substring( ).-
substring( ) Extracts a substring of a string.
-
toLowerCase( ) Returns a copy of the string, with all characters converted to lowercase.
-
toString( ) Returns the primitive string value.
-
toUpperCase( ) Returns a copy of the string, with all characters converted to uppercase.
-
valueOf( ) Returns the primitive string value.
Static Methods
-
String.fromCharCode( ) Creates a new string using the character codes passed as arguments.
HTML Methods
Since the earliest days of JavaScript, the String class has defined a number of methods that return a string modified by placing it within HTML tags. These methods have never been standardized by ECMAScript but can be useful in both client- and server-side JavaScript code that dynamically generates HTML. If you are willing to use nonstandard methods, you might create the HTML source for a bold, red hyperlink with code like this:
var s = "click here!";
var html = s.bold( ).link("javascript:alert('hello')").fontcolor("red");Because these methods are not standardized, they do not have individual reference entries in the pages that follow:
anchor(name)Returns a copy of the string, in an
<a name=>environment.-
big( ) Returns a copy of the string, in a
<big>environment.-
blink( ) Returns a copy of the string, in a
<blink>environment.-
bold( ) Returns a copy of the string, in a
<b>environment.-
fixed( ) Returns a copy of the string, in a
<tt>environment.fontcolor(color)Returns a copy of the string, in a
<font color=>environment.fontsize(size)Returns a copy of the string, in a
<font size=>environment.-
italics( ) Returns a copy of the string, in an
<i>environment.link(url)Returns a copy of the string, in an
<a href=>environment.-
small( ) Returns a copy of the string, in a
<small>environment.-
strike( ) Returns a copy of the string, in a
<strike>environment.-
sub( ) Returns a copy of the string, in a
<sub>-
sup( ) Returns a copy of the string, in a
<sup>environment.
Description
Strings are a primitive datatype in JavaScript. The String
class type exists to provide methods for operating on primitive
string values. The length
property of a String object specifies the number of characters in
the string. The String class defines a number of methods for
operating on strings; for example, there are methods for extracting
a character or a substring from the string or searching for a
character or a substring. Note that JavaScript strings are
immutable: none of the methods defined by the
String class allows you to change the contents of a string. Instead,
methods such as String.toUpperCase(
) return an entirely new string, without modifying the
original.
In implementations of JavaScript derived from the original
Netscape code base (such as the implementation in Firefox), strings
behave like read-only arrays of characters. For example, to extract
the third character from a string s, you can write s[2] instead of the more standard s.charAt(2). In addition, when the
for/in statement is applied to a
string, it enumerates these array indexes for each character in the
string. (Note, however, that the length property is not enumerated, as per
the ECMAScript specification.) Because this string-as-array behavior
is not standard, you should avoid using it.
Name
String.charAt( ): get the 'n'th character from a string — ECMAScript v1
Description
String.charAt( ) returns
the nth character of the string
string. The first character of the string
is numbered 0. If n is not between 0 and
string.length−1, this method returns an
empty string. Note that JavaScript does not have a character data
type that is distinct from the string type, so the returned
character is a string of length 1.
Name
String.charCodeAt( ): get the 'n'th character code from a string — ECMAScript v1
Description
charCodeAt( ) is like
charAt( ), except that it returns
the character encoding at a specific location, rather than returning
a substring that contains the character itself. If
n is negative or greater than or equal to
the string length, charCodeAt( )
returns NaN.
See String.fromCharCode( )
for a way to create a string from Unicode encodings.
Name
String.concat( ): concatenate strings — ECMAScript v3
Description
concat( ) converts each of
its arguments to a string (if necessary) and appends them, in order,
to the end of string. It returns the
resulting concatenation. Note that string
itself is not modified.
String.concat( ) is an
analog to Array.concat( ). Note
that it is often easier to use the + operator to perform string
concatenation.
Name
String.fromCharCode( ): create a string from character encodings — ECMAScript v1
Synopsis
String.fromCharCode(c1,c2, ...)
Description
This static method provides a way to create a string by
specifying the individual numeric Unicode encodings of its
characters. Note that as a static method, fromCharCode( ) is a property of the
String( ) constructor and is not
actually a method of strings or String objects.
String.charCodeAt( ) is a
companion instance method that provides a way to obtain the
encodings of the individual characters of a string.
Name
String.indexOf( ): search a string — ECMAScript v1
Synopsis
string.indexOf(substring)string.indexOf(substring,start)
Arguments
-
substring The substring that is to be searched for within
string.-
start An optional integer argument that specifies the position within
stringat which the search is to start. Legal values are 0 (the position of the first character in the string) tostring.length−1 (the position of the last character in the string). If this argument is omitted, the search begins at the first character of the string.
Description
String.indexOf( ) searches
the string string from beginning to end
to see if it contains an occurrence of
substring. The search begins at position
start within
string, or at the beginning of
string if
start is not specified. If an occurrence
of substring is found, String.indexOf( ) returns the position of
the first character of the first occurrence of
substring within
string. Character positions within
string are numbered starting with
zero.
If no occurrence of substring is
found within string, String.indexOf( ) returns −1.
Name
String.lastIndexOf( ): search a string backward — ECMAScript v1
Synopsis
string.lastIndexOf(substring)string.lastIndexOf(substring,start)
Arguments
-
substring The substring to be searched for within
string.-
start An optional integer argument that specifies the position within
stringwhere the search is to start. Legal values are from 0 (the position of the first character in the string) tostring.length−1 (the position of the last character in the string). If this argument is omitted, the search begins with the last character of the string.
Description
String.lastIndexOf( )
searches the string from end to beginning to see if it contains an
occurrence of substring. The search
begins at position start within
string, or at the end of
string if
start is not specified. If an occurrence
of substring is found, String.lastIndexOf( ) returns the position
of the first character of that occurrence. Since this method
searches from end to beginning of the string, the first occurrence
found is the last one in the string that occurs before the
start position.
If no occurrence of substring is
found, String.lastIndexOf( )
returns −1.
Note that although String.lastIndexOf( ) searches
string from end to beginning, it still
numbers character positions within string
from the beginning. The first character of the string has position
0, and the last has position string
.length−1.
Name
String.length: the length of a string — ECMAScript v1
Description
The String.length property
is a read-only integer that indicates the number of characters in
the specified string. For any string
s, the index of the last character is
s .length−1. The length property of a string is not
enumerated by a for/in loop and
may not be deleted with the delete operator.
Name
String.localeCompare( ): compare one string to another, using locale-specific ordering — ECMAScript v3
Synopsis
string.localeCompare(target)
Returns
A number that indicates the result of the
comparison. If string is "less than"
target, localeCompare( ) returns a number less
than zero. If string is "greater than"
target, the method returns a number
greater than zero. And if the strings are identical or
indistinguishable according to the locale ordering conventions,
the method returns 0.
Description
When the < and > operators are applied to strings,
they compare those strings using only the Unicode encodings of those
characters and do not consider the collation order of the current
locale. The ordering produced in this way is not always correct.
Consider Spanish, for example, in which the letters "ch" are
traditionally sorted as if they were a single letter that appeared
between the letters "c" and "d".
localeCompare( ) provides a
way to compare strings that does take the collation order of the
default locale into account. The ECMAScript standard does not
specify how the locale-specific comparison is done; it merely
specifies that this function utilize the collation order provided by
the underlying operating system.
Name
String.match( ): find one or more regular-expression matches — ECMAScript v3
Synopsis
string.match(regexp)
Description
match( ) searches
string for one or more matches of
regexp. The behavior of this method
depends significantly on whether regexp
has the "g" attribute or not (see Chapter 11, Pattern Matching with Regular Expressions
for full details on regular expressions).
If regexp does not have the "g"
attribute, match( ) searches
string for a single match. If no match is
found, match( ) returns null. Otherwise, it returns an array
containing information about the match that it found. Element 0 of
the array contains the matched text. The remaining elements contain
the text that matches any parenthesized subexpressions within the
regular expression. In addition to these normal array elements, the
returned array also has two object properties. The index property of the array specifies the
character position within string of the
start of the matched text. Also, the input property of the returned array is a
reference to string itself.
If regexp has the "g" flag,
match( ) does a global search,
searching string for all matching
substrings. It returns null if no
match is found, and it returns an array if one or more matches are
found. The contents of this returned array are quite different for
global matches, however. In this case, the array elements contain
each of the matched substrings within
string. The returned array does not have
index or input properties in this case. Note that
for global matches, match( ) does
not provide information about parenthesized subexpressions, nor does
it specify where within string each match
occurred. If you need to obtain this information for a global
search, you can use RegExp.exec(
).
Example
The following global match finds all numbers within a string:
"1 plus 2 equals 3".match(/\d+/g) // Returns ["1", "2", "3"]
The following nonglobal match uses a more complex regular expression with several parenthesized subexpressions. It matches a URL, and its subexpressions match the protocol, host, and path portions of the URL:
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = "Visit my home page at http://www.isp.com/~david";
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // Contains "http://www.isp.com/~david"
var protocol = result[1]; // Contains "http"
var host = result[2]; // Contains "www.isp.com"
var path = result[3]; // Contains "~david"
}See Also
RegExp, RegExp.exec( ), RegExp.test( ), String.replace( ), String.search( ); Chapter 11, Pattern Matching with Regular Expressions
Name
String.replace( ): replace substring(s) matching a regular expression — ECMAScript v3
Synopsis
string.replace(regexp,
replacement)
Arguments
-
regexp The RegExp object that specifies the pattern to be replaced. If this argument is a string, it is used as a literal text pattern to be searched for; it is not first converted to a RegExp object.
-
replacement A string that specifies the replacement text, or a function that is invoked to generate the replacement text. See the Description section for details.
Description
replace( ) performs a
search-and-replace operation on string.
It searches string for one or more
substrings that match regexp and replaces
them with replacement. If
regexp has the global "g" attribute
specified, replace( ) replaces
all matching substrings. Otherwise, it replaces only the first
matching substring.
replacement may be a string or a
function. If it is a string, each match is replaced by the string.
Note that the $ character has
special meaning within the replacement
string. As shown in the following table, it indicates that a string
derived from the pattern match is used in the replacement.
|
Characters |
Replacement |
|---|---|
|
|
The text that matched the 1st
through 99th parenthesized subexpression within
|
|
|
The substring that matched
|
|
|
The text to the left of the matched substring |
|
|
The text to the right of the matched substring |
|
|
A literal dollar sign |
ECMAScript v3 specifies that the
replacement argument to replace( ) may be a function instead of a
string. In this case, the function is invoked for each match, and
the string it returns is used as the replacement text. The first
argument to the function is the string that matches the pattern. The
next arguments are the strings that match any parenthesized
subexpressions within the pattern; there may be zero or more of
these arguments. The next argument is an integer that specifies the
position within string at which the match
occurred, and the final argument to the
replacement function is
string itself.
Example
To ensure that the capitalization of the word "JavaScript" is correct:
text.replace(/javascript/i, "JavaScript");
To convert a single name from "Doe, John" format to "John Doe" format:
name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1");
To replace all double quotes with double back and forward single quotes:
text.replace(/"([^"]*)"/g, "''$1''");
To capitalize the first letter of all words in a string:
text.replace(/\b\w+\b/g, function(word) {
return word.substring(0,1).toUpperCase( ) +
word.substring(1);
});See Also
RegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.search( ); Chapter 11, Pattern Matching with Regular Expressions
Name
String.search( ): search for a regular expression — ECMAScript v3
Synopsis
string.search(regexp)
Description
search( ) looks for a
substring matching regexp within
string and returns the position of the
first character of the matching substring, or −1 if no match was
found.
search( ) does not do
global matches; it ignores the g
flag. It also ignores the lastIndex property of
regexp and always searches from the
beginning of the string, which means that it always returns the
position of the first match in
string.
See Also
RegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.replace( ); Chapter 11, Pattern Matching with Regular Expressions
Name
String.slice( ): extract a substring — ECMAScript v3
Synopsis
string.slice(start,
end)
Arguments
-
start The string index where the slice is to begin. If negative, this argument specifies a position measured from the end of the string. That is, −1 indicates the last character, −2 indicates the second from last character, and so on.
-
end The string index immediately after the end of the slice. If not specified, the slice includes all characters from
startto the end of the string. If this argument is negative, it specifies a position measured from the end of the string.
Description
slice( ) returns a string
containing a slice, or substring, of
string. It does not modify
string.
The String methods slice(
), substring( ), and
the deprecated substr( ) all
return specified portions of a string. slice( ) is more flexible than substring( ) because it allows negative
argument values. slice( ) differs
from substr( ) in that it
specifies a substring with two character positions, while substr( ) uses one position and a length.
Note also that String.slice( ) is
an analog of Array.slice(
).
Example
var s = "abcdefg"; s.slice(0,4) // Returns "abcd" s.slice(2,4) // Returns "cd" s.slice(4) // Returns "efg" s.slice(3,-1) // Returns "def" s.slice(3,-2) // Returns "de" s.slice(-3,-1) // Should return "ef"; returns "abcdef" in IE 4
Name
String.split( ): break a string into an array of strings — ECMAScript v3
Synopsis
string.split(delimiter,
limit)
Arguments
-
delimiter The string or regular expression at which the
stringsplits.-
limit This optional integer specifies the maximum length of the returned array. If specified, no more than this number of substrings will be returned. If not specified, the entire string will be split, regardless of its length.
Description
The split( ) method creates
and returns an array of as many as limit
substrings of the specified string. These substrings are created by
searching the string from start to end for text that matches
delimiter and breaking the string before
and after that matching text. The delimiting text is not included in
any of the returned substrings, except as noted at the end of this
section. Note that if the delimiter matches the beginning of the
string, the first element of the returned array will be an empty
string—the text that appears before the delimiter. Similarly, if the
delimiter matches the end of the string, the last element of the
array (assuming no conflicting limit)
will be the empty string.
If no delimiter is specified, the
string is not split at all, and the returned array contains only a
single, unbroken string element. If
delimiter is the empty string or a
regular expression that matches the empty string, the string is
broken between each character, and the returned array has the same
length as the string does, assuming no smaller
limit is specified. (Note that this is a
special case because the empty strings before the first character
and after the last character are not matched.)
As noted earlier, the substrings in the array returned by this
method do not contain the delimiting text used to split the string.
However, if delimiter is a regular
expression that contains parenthesized subexpressions, the
substrings that match those parenthesized subexpressions (but not
the text that matches the regular expression as a whole) are
included in the returned array.
Note that the String.split(
) method is the inverse of the Array.join( ) method.
Example
The split( ) method is most
useful when you are working with highly structured strings. For
example:
"1:2:3:4:5".split(":"); // Returns ["1","2","3","4","5"]
"|a|b|c|".split("|"); // Returns ["", "a", "b", "c", ""]Another common use of the split(
) method is to parse commands and similar strings by
breaking them down into words delimited by spaces:
var words = sentence.split(' ');It is easier to split a string into words using a regular expression as a delimiter:
var words = sentence.split(/\s+/);
To split a string into an array of characters, use the empty
string as the delimiter. Use the limit
argument if you only want to split a prefix of the string into an
array of characters:
"hello".split(""); // Returns ["h","e","l","l","o"]
"hello".split("", 3); // Returns ["h","e","l"]If you want the delimiters or one or more portions of the delimiter included in the returned array, use a regular expression with parenthesized subexpressions. For example, the following code breaks a string at HTML tags and includes those tags in the returned array:
var text = "hello <b>world</b>"; text.split(/(<[^>]*>)/); // Returns ["hello ","<b>","world","</b>",""]
Name
String.substr( ): extract a substring — JavaScript 1.2; deprecated
Synopsis
string.substr(start,
length)
Arguments
-
start The start position of the substring. If this argument is negative, it specifies a position measured from the end of the string: −1 specifies the last character, −2 specifies the second-to-last character, and so on.
-
length The number of characters in the substring. If this argument is omitted, the returned substring includes all characters from the starting position to the end of the string.
Description
substr( ) extracts and
returns a substring of string. It does
not modify string.
Note that substr( )
specifies the desired substring with a character position and a
length. This provides a useful alternative to String.substring( ) and String.splice( ), which specify a
substring with two character positions. Note, however, that this
method has not been standardized by ECMAScript and is therefore
deprecated.
Example
var s = "abcdefg"; s.substr(2,2); // Returns "cd" s.substr(3); // Returns "defg" s.substr(-3,2); // Should return "ef"; returns "ab" in IE 4
Name
String.substring( ): return a substring of a string — ECMAScript v1
Synopsis
string.substring(from,
to)
Arguments
-
from A nonnegative integer that specifies the position within
stringof the first character of the desired substring.-
to A nonnegative optional integer that is one greater than the position of the last character of the desired substring. If this argument is omitted, the returned substring runs to the end of the string.
Description
String.substring( ) returns
a substring of string consisting of the
characters between positions from and
to. The character at position
from is included, but the character at
position to is not included.
If from equals
to, this method returns an empty (length
0) string. If from is greater than
to, this method first swaps the two
arguments and then returns the substring between them.
It is important to remember that the character at position
from is included in the substring but
that the character at position to is not
included in the substring. While this may seem arbitrary or
counterintuitive, a notable feature of this system is that the
length of the returned substring is always equal to
to-from.
Note that String.slice( )
and the nonstandard String.substr(
) can also extract substrings from a string. Unlike those
methods, String.substring( ) does
not accept negative arguments.
Name
String.toLocaleLowerCase( ): convert a string to lowercase — ECMAScript v3
Name
String.toLocaleUpperCase( ): convert a string to uppercase — ECMAScript v3
Name
String.toString( ): return the string — ECMAScript v1: Overrides Object.toString( )
Name
String.valueOf( ): return the string — ECMAScript v1: Overrides Object.valueOf( )
Name
SyntaxError: thrown to signal a syntax error — ECMAScript v3: Object → Error → SyntaxError
Constructor
new SyntaxError( )
new SyntaxError(message)Arguments
-
message An optional error message that provides details about the exception. If specified, this argument is used as the value for the
messageproperty of the SyntaxError object.
Returns
A newly constructed SyntaxError object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the SyntaxError(
) constructor is called as a function, without the
new operator, it behaves just
as it does when called with the new operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See
Error.messagefor details.-
name A string that specifies the type of the exception. All SyntaxError objects inherit the value "SyntaxError" for this property.
Name
TypeError: thrown when a value is of the wrong type — ECMAScript v3: Object → Error → TypeError
Constructor
new TypeError( )
new TypeError(message)Arguments
-
message An optional error message that provides details about the exception. If specified, this argument is used as the value for the
messageproperty of the TypeError object.
Returns
A newly constructed TypeError object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the TypeError( )
constructor is called as a function, without the new operator, it behaves just as it does
when called with the new
operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See
Error.messagefor details.-
name A string that specifies the type of the exception. All TypeError objects inherit the value "TypeError" for this property.
Description
An instance of the TypeError class is thrown when a value is
not of the type expected. This happens most often when you attempt
to access a property of a null or
undefined value. It can also
occur if you invoke a method defined by one class on an object that
is an instance of some other class, or if you use the new operator with a value that is not a
constructor function, for example. JavaScript implementations are
also permitted to throw TypeError objects when a built-in function
or method is called with more arguments than expected. See Error for details about throwing and
catching exceptions.
Name
undefined: the undefined value — ECMAScript v3
Description
undefined is a global
property that holds the JavaScript undefined value. This is the same value
that is returned when you attempt to read the value of a nonexistent
object property. The undefined
property is not enumerated by for/in loops and cannot be deleted with
the delete operator. Note that
undefined is not a constant and
can be set to any other value, something that you should take care
not to do.
When testing a value to see whether it is undefined, use the
=== operator, because the
== operator treats the undefined value as equal to null.
Name
unescape( ): decode an escaped string — ECMAScript v1; deprecated in ECMAScript v3
Description
unescape( ) is a global
function that decodes a string encoded with escape( ). It decodes
s by finding and replacing character
sequences of the form %
xx and %u xxxx (where
x represents a hexadecimal digit) with
the Unicode characters \u00
xx and \
u
xxxx.
Although unescape( ) was
standardized in the first version of ECMAScript, it has been
deprecated and removed from the standard by ECMAScript v3.
Implementations of ECMAScript are likely to implement this function,
but they are not required to. You should use decodeURI( ) and decodeURIComponent( ) instead of unescape( ). See escape( ) for more details and an
example.
Name
URIError: thrown by URI encoding and decoding methods — ECMAScript v3: Object → Error → URIError
Constructor
new URIError( )
new URIError(message)Returns
A newly constructed URIError object. If the
message argument is specified, the
Error object uses it as the value of its message property; otherwise, it uses an
implementation-defined default string as the value of that
property. When the URIError( )
constructor is called as a function without the new operator, it behaves just as it does
when called with the new
operator.
Properties
-
message An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See
Error.messagefor details.-
name A string that specifies the type of the exception. All URIError objects inherit the value "URIError" for this property.
Description
An instance of the URIError class is thrown by decodeURI( ) and decodeURIComponent( ) if the specified
string contains illegal hexadecimal escapes. It can also be thrown
by encodeURI( ) and encodeURIComponent( ) if the specified
string contains illegal Unicode surrogate pairs. See Error for details about throwing and
catching exceptions.
If you enjoyed this excerpt, buy a copy of JavaScript: The Definitive Guide.
