Definition and usage
slice() method returns selected elements from an existing array.
Syntax
arrayObject.slice(start,end)
Parameters
Description
start Required. Specifies where to start the selection. If negative, it specifies the position from the end of the array. That is, -1 refers to the last element, -2 refers to the second to last element, and so on.
end Optional. Specifies where the selection ends. This parameter is the array index at the end of the array fragment. If this parameter is not specified, the split array contains all elements from start to the end of the array. If this parameter is negative, it specifies the elements starting from the end of the array.
Return Value
Returns a new array containing the elements in arrayObject from start to end (excluding this element).
Description
Please note that this method does not modify the array, but returns a subarray. If you want to delete a segment of elements from an array, you should use the method Array.splice().
Tips and Notes
Note: You can use negative values to select elements from the tail of an array.
Note: If end is not specified, the slice() method will select all elements from start to the end of the array.
Example Example 1
In this example, we will create a new array and then display the elements selected from it:
Output:
George,John,Thomas
John,Thomas
George, John, Thomas
Example 2
In this example, we will create a new array and then display the elements selected from it:
Output:
George,John,Thomas,James,Adrew,Martin
Thomas,James
George,John,Thomas,James,Adrew,Martin
TIY
slice()
How to use slice() to display selected elements from an existing array.