How To Fill Specified Elements To An Array In JavaScript

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

In Java script we can fills the specified elements in an array with a static value using fill() method so today we are going to discuss how to fill specified elements in an array by static value.

How To Fill Specified Elements To An Array In JavaScript

The fill() method fills the specified elements in an array with a static value.

You can specify the position of where to start and end the filling. If not specified, all elements will be filled.

Syntax and Usage

array.fill(value, start, end)
 

Parameter Values

value  ->   Required. The value to fill the array with
start  ->   Optional. The index to start filling the array (default is 0)
end    ->   Optional. The index to stop filling the array (default is array.length)
 

Let's start

Example(1)

1.Create array elements

var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];

2.Implement code to fill specified element with new static value
 
document.getElementById("demo").innerHTML = languages;

function languages_function() {
    document.getElementById("demo").innerHTML = languages.fill("HTML");
}


Example(2)
<script>
    var languages = ["PHP", "JAVASCRIPT", "PYTHON", "C++"];
    document.getElementById("demo").innerHTML = languages;

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

In above example we specified index number to be filled with new value
 

Compelete Code For Filling Specified Elements To An Array In JavaScript.
<!DOCTYPE html>
<html>
<head>
    <title>How To Fill Specified Elements To An Array 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> Fill Specified Elements To An Array 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.fill("HTML",3);
    }
</script>

Related Post