Sunday, 2 September 2018

JavaScript: push: Append an element to array

'push' function is used to add an element to the end of array.

Syntax
array.push(element);

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 will see following text.

Elements in Array are : 2

Pushing element
Elements in Array are : 2 3

Pushing element
Elements in Array are : 2 3 5

Pushing element
Elements in Array are : 2 3 5 7

Pushing element
Elements in Array are : 2 3 5 7 11




Previous                                                 Next                                                 Home

No comments:

Post a Comment