JavaScript : How to Append Values to an Array ?

JavaScript : How to Append Values to an Array ?

Asked on October 31, 2018 in Javascript.
Add Comment


  • 1 Answer(s)

        use the JavaScript push() method to append values to an array.

        For ex:

    <script>
    var persons = ["Harry", "John", "Clark"];
    // Append a single value to persons array
    persons.push("Peter");
    console.log(persons);
    // Prints: ["Harry", "John", "Clark", "Peter"]
    // Append multiple values to persons array
    persons.push("Rohn", "Alice");
    console.log(persons);
    // Prints: ["Harry", "John", "Clark", "Peter", "Rohn", "Alice"]
    // Loop through persons array and display all the values
    for(var i = 0; i < persons.length; i++){
    document.write("<p>" + persons[i] + "</p>");
    }
    </script>
    
    Answered on October 31, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.