slice()
returns the sub-array.
The slice()
method may accept one or two arguments:
slice(startingPoint)
returns sub-array
between startingPoint
and the end of the array.
slice(startingPoint,endPosition)
returns
sub-array between the startingPosition
and
endPosition
, not including the item in the
end position.
slice()
does not affect the original array in any way.
slice() |
Yes | Yes | Yes | Yes | Yes |
array.slice(start,end)
Parameter | Description |
---|---|
start | Required. An integer to set where to start the selection. The first element starts at 0. Negative numbers selects from the end of an array. |
end | Optional. An integer to set where to end the selection. If omitted, default to the end of the array. Negative numbers selects from the end of an array |
A new Array containing the selected elements.
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
console.log(colors2); //B,C,D,E
console.log(colors3); //B,C,D
The code above generates the following result.
If either the start or end position of slice() is a negative number, then the number is subtracted from the length of the array.
For the array in the following code,
arrayWithFiveItem.slice(-2, -1)
is the same as arrayWithFiveItem.slice(3, 4)
.
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.slice(-2,-1);
var colors3 = colors.slice(3,4);
console.log(colors2); //D
console.log(colors3); //D
If the end position is smaller than the start, then an empty array is returned.
The code above generates the following result.