How To Use Array copyWithin Function In JavaScript

admin_img Posted By Bajarangi soft , Posted On 24-09-2020

In Java Script we can copy and paste array elements to another position in the array, overwriting the existing values by using copywithin function today we are going to discuss how to use copywithin function in javascript.

How To Use Array copyWithin Function In JavaScript

The copyWithin() method copies array elements to another position in the array, overwriting the existing values.

This method will never add more items to the array.

Syntax and Usage

array.copyWithin(target, start, end)
 

Parameter Values

target   -> Required. The index position to copy the elements to
start  -> Optional. The index position to start copying elements from  (default is 0)
end        -> Optional. The index position to stop copying elements from (default is array.length)
 
Let's Start 

Example(1)

1.Create array.
var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];

2.Now Implement code to copy specified array element 
document.getElementById("demo").innerHTML = languages;

function languages_function() {
    document.getElementById("demo").innerHTML = languages.copyWithin(2,0);
}


Example(2)
<script>
    var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
    document.getElementById("demo").innerHTML = fruits;

    function myFunction() {
        document.getElementById("demo").innerHTML = fruits.copyWithin(2,0,2);
    }
</script>

In above Example copywithin method replace array elements by banana and orange in the place of apple and mango 

Complete code of array copy within method in java script
<!DOCTYPE html>
<html>
<head>
    <title>How To Use Array copyWithin() Function In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>Array copyWithin() Function In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <button class="btn btn-primary" onclick="languages_function()">Click it</button>
        <h1 id="demo"></h1>
    </div>
    <br>
</div>
</body>
</html>
<script>
    var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];
    document.getElementById("demo").innerHTML = languages;

    function languages_function() {
        document.getElementById("demo").innerHTML = languages.copyWithin(2,0);
    }
</script>

 

Related Post