简体   繁体   中英

How do I add a new Object to a Array, in JavaScript?

How do I add newObject to my array shapeArr ? Do I need to add a for loop?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <style type="text/css">
            ul{ list-style-type:none;}
            div{ width:300px; height:200px; background-color:#0066cc; }
        </style>    
    </head>
    <body>
        <ul id="placeholder"></ul>
        <a href="#" id="btn">Add</a>

        <script type="text/javascript">

            function add(){

                function draw(){

                    var template = document.createElement("li");
                    template.innerHTML = "<div></div><a href='#' class='update'>Update</a>";                

                    document.getElementById("placeholder").appendChild(template);
                }

                var newObject = new draw();

                var shapeArr = [];

            }

            var btn = document.getElementById("btn");
            btn.addEventListener("click", add, false);

        </script>       
    </body>
</html>

使用Array.push()

shapeArr.push(newObject);

You can use the push() method of the JavaScript Array to add new elements to the end:

var newObject = new draw();
var shapeArr  = [];

// add the new Object
shapeArr.push(newObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM