JavaScript Array method: slice()
[this page | pdf | back links]
The slice() method (when applied to a JavaScript
array) selects
a part of an array and returns that part.
It
has the following syntax with the following parameters. It returns a new
array containing the selected elements.
array.slice(start, end)
Parameter
|
Required / Optional
|
Description
|
start
|
Optional
|
An integer specifying
where to start the selection. Negative numbers are treated as selecting from
the end of the array. Default is zero
|
end
|
Optional
|
An integer that
specifies where to end the selection. Negative numbers are treated as
selecting from the end of the array. Default is to select from start
to the end of the array
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
var h = [-1, 2, 3, 4];
document.getElementById("Example").innerHTML =
'var h = [-1, 2, 3, 4];<br>' +
'var x = h.slice(1,3);';
document.getElementById("Result").innerHTML = h.slice(1,3);
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArraySlice() {
var h = [1, 2, 3]; return !!h.slice;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays