HTML and CSS Reference
In-Depth Information
The method reverses all the items so that 'soccer' becomes the last item in the array and
'badminton' becomes the first item.
Using the sort method
The sort method sequences the items in the array in ascending order. In the sports array, the
sort would be alphabetical, as shown in the following example:
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby',
'tennis', 'badminton');
alert(sports.indexOf('soccer'));
sports.sort();
alert(sports.indexOf('soccer'));
The result is that the sports array is now sorted. The alert boxes show the index of the
'soccer' element before and after the sort, demonstrating that the element has moved from
position 0 to position 6 in the array.
Using the slice method
The slice method takes out one or more items in an array and moves them to a new array.
Consider the following array with the list of sports:
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby',
'tennis', 'badminton');
var someSports = sports.slice(1, 2);
The slice method takes two parameters: the indexes where the slice operation should
begin and end. The ending index isn't included in the slice. All copied elements are returned
as an array from the slice method. In this example, because 'basketball' is at index 1 and the
ending index is specified at index 2, the resulting array someSports contains only one element:
'basketball'.
Using the splice method
The splice method provides a way to replace items in an array with new items. The following
code demonstrates this:
var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'cricket', 'rugby',
'tennis', 'badminton');
var splicedItems = sports.splice(1, 3, 'golf', 'curling', 'darts');
The splice method returns an array containing the items that are spliced out of the source
array. The first parameter is the index in the array where the splice operation should start.
The second parameter is the number of items to splice, starting from the index specified in
the first parameter. The optional last parameter lists items that are to replace the items being
spliced out. The list doesn't have to be the same length as the items being spliced out. In
fact, if the last parameter is omitted, the spliced items are simply removed from the array and
not replaced. In this example, three items are replaced, starting at index 1. So, 'basketball',
'hockey', and 'football' are replaced with 'golf', 'curling', and 'darts'.
 
Search WWH ::




Custom Search