|
| HOW TO SLICE ELEMENTS OF AN ARRAY INTO PIECES (NEW ARRAY) USING THE JAVACSRIPT slice() METHOD
When working with javascript arrays, it is possible to slice an array and create a new array with some of the elements of the original array. This is achieved by using the javascript slice() method.
The general format is:
Array.slice(index start, index end);
Where Array is the name of an array. This method takes two arguments, the index number to start slice from and the index number to end slice. The second argument may be a negative numer to indicate the position from the end of the array. If only a single argument is used as index number, then the array slice method will start the slice from this index number to end of the original string. Always remember that index numbers are counted from 0 onwards.
Example with both arguments supplied:
var OriginalColor= new Array("blue", "green", "red", "yellow");
var NewColor=OriginalColor.slice(1,3);
alert(NewColor); // displays green, red
Example with one argument supplied:
var OriginalColor= new Array("blue", "green", "red", "yellow");
var NewColor=OriginalColor.slice(1);
alert(NewColor); // green, red and yellow
Example with negative second argument supplied:
var OriginalColor= new Array("blue", "green", "red", "yellow");
var NewColor=OriginalColor.slice(1, -1);
alert(NewColor); // green, red
Now Read:
|
|