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++"];
document.getElementById("demo").innerHTML = languages;
function languages_function() {
document.getElementById("demo").innerHTML = languages.fill("HTML");
}
<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
<!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>