Sunday, January 18, 2009

Cutting a Slice of an Array in Javascript

The slice() method is to an Array object what the substring() method is to a String object.
You simply tell the method which elements you want to be sliced. This would be useful, for
example, if you wanted to slice information being passed using a URL.
The slice() method takes two parameters: the index of the first element of the slice, which
will be included in the slice, and the index of the final element, which won’t be. To access the
second, third, and fourth values from an array holding five values in all, we use the indexes 1
and 4:

The new array stores the numbers in a new zero-based array, so slicing indexes 0, 1, and 2
gives us the following:
Two
Three
Four
The original array is unaffected, but you could overwrite the Array object in the variable by
setting it to the result of the slice() method if you needed to:
fullArray = fullArray.slice( 1, 4 );


Thanks
Amita Vashisht

No comments:

Post a Comment