Using the Java Script Array Object
array.slice
The slice method allows you to extract a contiguous series of elements from
an array. The code below creates an array named animal that is initialized with
a seemingly nonsense string of characters. The slice method is then used to
extract the word bird from elements within the array.
var animal = new Array('h','f','b','i','r','d','j','s');
var arrOut = animal.slice(2,6);
document.write(arrOut.join(""));
Output:
bird
The first parameter passed to the slice method is the starting index for the extraction.
The second parameter is the ending index for the extraction. Note that the extraction
does not include the value of the element at the index of the second parameter, only
up to that element. You have to add 1 to the second parameter to include the next value
in the array. If you don't specify a second parameter, the extraction includes all elements
to the end of the array.
Note that I used the join method to replace the default comma separators with an empty
string for display formatting purposes.
array.splice
The slice method allows you to replace values in an array. The code below creates
an array that is initialized with the names of some NFL football teams. The slice method
is then used to replace the "Packers" with the "Eagles", and replace the "Steelers" with
the "Chargers".
var Teams = new Array("Bears","Packers","Vikings","Steelers","Saints","Cowboys","Giants");
var removed = Teams.splice(1, 3, "Eagles","Chargers");
document.write(Teams);
After execution of the code, the Teams array contains "Bears","Eagles","Chargers",
"Saints","Cowboys","Giants". Note that the slice method modifies the original array.
The slice method returns an array containing the removed elements. You don't
need to assign the returned value to a variable if you don't intend to use it.
splice(startIndex, how_many, value1, ...)
The slice method deletes how_many array elements starting from startIndex,
and replaces them with values provided in the third parameter. Note in the example that
I removed three elements, and replaced them with only two elements. If you specify a
different number of elements to insert than the number you remove, the array will have
a different length after the call. If you leave out the third parameter, the splice
method simply removes how_many elements from the array. If you leave out the how_many
parameter, all elements after startIndex are removed.
array.reverse
The reverse method reveres the order of the elements in an array.
var digit = [1, 2 ,3];
digit.reverse();
document.write(digit);
Output:
3,2,1
Note that the reverse method modifies the original array.
|