How To Delete Element Without Using Array Method In JavaScript

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

We know we have pop() and shift() methods are there to delete or remove array elements but We can delete array elements without using methods in java script . so today we are discus how to delete array element in java script

How To Delete Element Without Using Array Method In JavaScript

Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:


Using delete may leave undefined holes in the array. Use pop() or shift() instead.


Let's start

Example(1)

1.Create array elements

var Animals = ["Zebra", "Squirrel","Loin", "Yak","Rhinoceros"];


2.Implement code to delete array element
document.getElementById("demo1").innerHTML =
    "The First Animal is: " + Animals[0];

function animal_lists() {


    delete Animals[0];
    document.getElementById("demo1").innerHTML =
        "The First Animal is: " + Animals[0];
}
 

Complete code for deleting array elements 

<!DOCTYPE html>
<html>
<head>
    <title>Deleting Elements Without Methods 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>Deleting Elements Without Methods In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <button class="btn btn-primary" onclick="animal_lists()">Click it</button>
        <h1 id="demo1"></h1>
    </div>
    <br>
</div>
</body>
</html>

<script>
    var Animals = ["Zebra", "Squirrel","Loin", "Yak","Rhinoceros"];
    document.getElementById("demo1").innerHTML =
        "The First Animal is: " + Animals[0];
    function animal_lists() {
        delete Animals[0];
        document.getElementById("demo1").innerHTML =
            "The First Animal is: " + Animals[0];
    }
</script>

 

Related Post