HTML and CSS Reference
In-Depth Information
The array returned by the concat method and stored in the combinedSports variable
contains all the elements from both arrays in sequence. The contents of the moreSports array
appear after the elements of the sports array in this example.
Using the indexOf and lastIndexOf methods
The indexOf method provides a way to find the index of a known element. The following code
sample demonstrates this:
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby',
'tennis', 'badminton');
var index = sports.indexOf('football', 0);
This example calls the indexOf method to determine the index of the element 'football'.
The indexOf method accepts two parameters: what to search for and the index at which to
begin searching. This example searches the entire array, so the search starts at index 0. The
result from this call to the indexOf method is 3 , because the element is found in the fourth
position. If the element being sought isn't found, the method returns a value of -1 .
The indexOf method uses the identity operator to check for equality, which means that
if an array contains strings such as '1', '2', and '3' and you're searching for the integer 3, the
result is -1 because the equality operation returns false for all elements in the array. The
indexOf method searches in ascending index order. To search in descending order—that is,
to search from the end of the array to the beginning—use the lastIndexOf method, which
accepts the same parameters.
Using the join method
The join method joins all the elements in an array into a single string separated by a specified
string separator. For example, to convert an array of strings into a comma-separated list, you
could use the following code:
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby',
'tennis', 'badminton');
var joined = sports.join(',');
The join method accepts a string as a parameter, which is the string used as a delimiter
to separate the values in the array. The result is a string of all the elements separated by the
string passed into the join method.
Using the reverse method
The reverse method reverses the sequence of all elements in the array. This example reverses
the sports array:
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby',
'tennis', 'badminton');
sports.reverse();
 
Search WWH ::




Custom Search