Changing Elements
Array elements are accessed using their index number:
Array indexes start with 0. [0] is the first array element, [1] is the second, [2] is the third ...
Let's start
Example(1)
1.Create array elements
var Animals = ["Zebra", "Squirrel","Loin", "Yak","Rhinoceros"];
document.getElementById("demo1").innerHTML = Animals;
function animal_lists() {
Animals[0] = "Tiger";
document.getElementById("demo1").innerHTML = Animals;
}
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits[fruits.length] = "Kiwi";
document.getElementById("demo").innerHTML = fruits;
}
</script>
In above example The length
property provides an easy way to append a new element to an array
<!DOCTYPE html>
<html>
<head>
<title>Change Single Array Element Using 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>Change Single Array Element Using JavaScript</h1>
</div>
<br>
<div class="well">
<button class="btn btn-primary" onclick="animal_lists()">Click it</button>
<h1 id="demo1"></h1>
<button class="btn btn-primary" onclick="fruits_Function()">Click it</button>
<h1 id="demo2"></h1>
</div>
<br>
</div>
</body>
</html>
<script>
var Animals = ["Zebra", "Squirrel","Loin", "Yak","Rhinoceros"];
document.getElementById("demo1").innerHTML = Animals;
function animal_lists() {
Animals[0] = "Tiger";
document.getElementById("demo1").innerHTML = Animals;
}
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo2").innerHTML = fruits;
function fruits_Function() {
fruits[fruits.length] = "Kiwi";
document.getElementById("demo2").innerHTML = fruits;
}
</script>