How To Change Single Array Element Using JavaScript

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

array element can be replace in java script using index value so we can change that particular data and we new data today we are going to discuss how to change array element

How To Change Single Array Element Using JavaScript

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"];

2.Now we specify index number to be change the array element
document.getElementById("demo1").innerHTML = Animals;

function animal_lists() {
    Animals[0] = "Tiger";
    document.getElementById("demo1").innerHTML = Animals;
}


Example(2)
<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


Complete code for changing array elements in java script
<!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>

Related Post