TypedArray.copyWithin() function in JavaScript


The copyWithin() function of the TypedArray object copies the contents of this TypedArray within itself. This method accepts three numbers where first number represents the index of the array at which the copying of elements should be started and, the next two numbers represents start and end elements of the array from which the data should be copied (taken).

Syntax

Its Syntax is as follows

obj.copyWithin(3, 1, 3);

Example

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55 ]);
      document.write("Contents of the typed array: "+int32View);
      int32View.copyWithin(5, 0, 5);
      document.write("<br>");
      document.write("Contents of the typed array after copy: "+int32View);
   </script>
</body>
</html>

Output

Contents of the typed array: 21,64,89,65,33,66,87,55
Contents of the typed array after copy: 21,64,89,65,33,21,64,89

Example

It is not mandatory to pass the third parameter to this function (end elements of the array from which the data should be copied) it will copy till the end of the array.

 Live Demo

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var int32View = new Int32Array([21, 64, 89, 65, 33, 66, 87, 55 ]);
      document.write("Contents of the typed array: "+int32View);
      int32View.copyWithin(5, 0);
      document.write("<br>");
      document.write("Contents of the typed array after copy: "+int32View);
   </script>
</body>
</html>

Output

Contents of the typed array: 21,64,89,65,33,66,87,55
Contents of the typed array after copy: 21,64,89,65,33,21,64,89

Updated on: 25-Jun-2020

34 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements