Availability
JavaScript 1.1; JScript 2.0; ECMAScript v1
Synopsis
array.sort( ) array.sort(orderfunc)Arguments
orderfunc
An optional function used to specify the sorting order.
Returns
A reference to the array. Note that the array is sorted in place and
no copy is made.
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,
a is "less than"
b and should appear before
b in the sorted array. - Zero, if a and
b are equivalent for the purposes of this
sort. - A value greater than zero, if a is
"greater than" b for 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, 1111
•
Table of Contents
•
Index
•
Reviews
•
Examples
•
Reader Reviews
•
Errata
JavaScript: The Definitive Guide, 4th Edition
By
David Flanagan
Publisher
: O'Reilly
Pub Date
: November 2001
ISBN
: 0-596-00048-0
Pages
: 936
Slots
: 1
This fourth edition of the definitive reference to
JavaScript, a scripting language that can be embedded
directly in web pages, covers the latest version of the
language, JavaScript 1.5, as supported by Netscape 6 and
Internet Explorer 6. The book also provides complete
coverage of the W3C DOM standard (Level 1 and Level 2),
while retaining material on the legacy Level 0 DOM for
backward compatibility.