Sunday 2 September 2018

JavaScript: shift: Remove first element from array

shift function is used to remove an element from array.

Syntax
arrayName.shift()

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        var array = [2];

        function printArray(arr) {
            document.write("<br />Elements in Array are : ");
            for (var i = 0; i < arr.length; i++) {
                document.write(arr[i] + " ");
            }
            document.write("<br />");
        }

        printArray(array);

        document.write("<br />Pushing element");
        array.push(3);
        printArray(array);

        document.write("<br />Pushing element");
        array.push(5);
        printArray(array);

        document.write("<br />Pushing element");
        array.push(7);
        printArray(array);

        document.write("<br />Pushing element");
        array.push(11);
        printArray(array);
    </script>
</body>

</html>


Open above page in browser, you can able to see following data.


Elements in Array are : 2 3 5 7 11

Removing first element
Elements in Array are : 3 5 7 11

Removing first element
Elements in Array are : 5 7 11

Removing first element
Elements in Array are : 7 11

Removing first element
Elements in Array are : 11



Previous                                                 Next                                                 Home

No comments:

Post a Comment