/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: copyWithin()

[this page | pdf | back links]

The copyWithin() method (when applied to a JavaScript array) copies elements to and from specified positions.

 

It has the following syntax with the following parameters. It returns an array (the changed array).

 

array.copyWithin(target, start, end)

 

Parameter

Required / Optional

Description

target

Required

The index position where elements start to be copied to

start

Optional

The index position where elements start to be copied from (default is zero)

end

Optional

The index position where elements stop being copied from (default is array.length

 

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"];
document.getElementById("Example").innerHTML =
  'var h = ["a","b","c","d"];' + '<br>' +
  'var x = h.copyWithin(2,0);';
document.getElementById("Result").innerHTML
  = h.copyWithin(2,0);
</script>

</body>
</html>

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


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile