JavaScript » Array » slice

Syntax:
Array.slice(begin[,end])

The slice method creates a new array from a selected section of an array.

The original array is unaffected by this but, if a string or number in one array is altered, it is not reflected in the other, whereas a change to a referenced object can be seen in both Array objects. The slice method uses the zero-based array index to determine the section out of which to create the new array. It extracts up to, but not including, the 'end' element (if no 'end' is specified, the default is the very last element).

If you use a negative index for the 'end', this specifies an element so many places from the end.

Examples

Code:
trees = ["oak", "ash", "beech", "maple", "sycamore"]
document.write(trees.slice(1,4))
Output:
ash,beech,maple
Explanation:

This code creates an array called 'trees' and then displays a 'slice' of it.

Code:
trees = ["oak", "ash", "beech", "maple", "sycamore"]
document.write(trees.slice(1,-2))
Output:
ash,beech
Explanation:

This code would display the second through the third to last elements of the array: