Array.slice

Extracts a section of an array and returns a new array.

Method of Array

Syntax

array.slice( begin [, end ])

Parameters

Parameter Description
begin Zero-based index at which to begin extraction.
end Zero-based index at which to end extraction:
slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3)
As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second to last element in the sequence.
If end is omitted, slice extracts to the end of the sequence.

Description

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:
For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.
If a new element is added to either array, the other array is not affected.

Example

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.