如何在JavaScript中向数组添加新对象?

时间:2012-10-16 23:46:18

标签: javascript

如何将newObject添加到我的阵列shapeArr? 我是否需要添加for循环?

<!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>

2 个答案:

答案 0 :(得分:1)

使用Array.push()

shapeArr.push(newObject);

答案 1 :(得分:0)

您可以使用JavaScript数组的push()方法向末尾添加新元素:

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

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