/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: splice()

[this page | pdf | back links]

The splice() method (when applied to a JavaScript array) adds / removes elements to / from the array.

 

It has the following syntax with the following parameters. It returns a new array containing the removed items, if any.

 

array.splice(index, numberremoved, item1, item2, …)

 

Parameter

Required / Optional

Description

index

Required

Integer specifying position at which to add/remove items. Negative numbers specify from end of array

numberremoved

Optional

Number of items to be removed (if set to zero then no items will be removed)

item1, item2, …

Optional

New item(s) to be added to 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 = ["a", "b", "c", "d"];
var y = h.splice(1, 2, "e", "f", "g")
document.getElementById("Example").innerHTML =
  'var h = ["a", "b", "c", "d"];<br>' +
  'var y = h.splice(1, 2, "e", "f", "g");<br>' +
  'var x = h + "|" + y;';
document.getElementById("Result").innerHTML = h + "|" + y;
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArraySplice() {
  var h = [1, 2, 3]; return !!h.splice;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile