Array methods

Provides a reference of array methods.

Table 1. Array methods
Syntax Effect
array.join([ separator ])

Returns a string that contains the elements of the array converted to strings, concatenated together and separated with separator. If separator is omitted, it is taken to be ",". Elements that are not initialized are converted to the empty string. See also the string method split.

Example: Suppose that the array a has been created with

a = new Array("foo", 12, true)

Then:

a.join("//") –> "foo//12//true"

a.join() –> "foo,12,true"

array.sort([ function ])

Sorts the array. The elements are sorted in place; no new array is created.

If function is not provided, array is sorted lexicographically: Elements are compared by converting them to strings and using the < operator. With this order, the number 20 would come before the number 5, since "20" < "5" is true.

If function is supplied, the array is sorted according to the return value of this function. This function must take two arguments x and y and return:

-1 if x is smaller than y

0 if x is equal to y

1 if x is greater than y

Example: Suppose that the function compareLength is defined as

function compareLength(x, y) {if (x.length < y.length) return -1; else if (x.length == y.length) return 0; else return 1; }

and that the array a has been created with:

a = new Array("giraffe", "rat", "brontosaurus")

Then a.sort() will reorder its elements as follows:

"brontosaurus" "rat" "giraffe"

while a.sort(compareLength) will reorder them as follows:

"rat" "giraffe" "brontosaurus"
array.reverse()

Transposes the elements of the array: the first element becomes the last, the second becomes the second to last, and so on. The elements are reversed in place; no new array is created.

Example: Suppose that the array a has been created with

a = new Array("foo", 12, "hello", true, false)

Then a.reverse() changes a so that:

a[0] false

a[1] true

a[2] "hello"

a[3] 12

a[4] "foo"

array.toString() Returns the string "[object Object]".