如何使用Javascript push()将一组值推送到数组?

时间:2013-10-26 00:43:32

标签: javascript json function

有人能在这里发现错误吗?检查点1触发但不检查检查点2.无法弄清楚我的陈述有什么问题。

    <script>
        function shoppingCart() {

            var item,
                price,
                qty,
                items = {
                    itemID: "B17",
                    itemPrice: 17,
                    itemQty: 1
                    };

        function addItem(item, price, qty) {
             alert("checkpoint 1");
               items.push({
               itemID: item,                  
               itemPrice: price,
               itemQty: qty
               });
             alert("checkpoint 2");

        };

};
        cart = new shoppingCart();

        cart.addItem("b4",14,1);
        alert(cart.items.itemID);
    </script>

2 个答案:

答案 0 :(得分:3)

items = {
    itemID: "B17",
    itemPrice: 17,
    itemQty: 1
};

不是数组。它应该是:

items =[{
    itemID: "B17",
    itemPrice: 17,
    itemQty: 1
}];

答案 1 :(得分:2)

问题是项目不是数组,而是对象。小提琴:http://jsfiddle.net/pCc9w/

所有代码,已修复:

        function shoppingCart() {

            var item,
                price,
                qty;
                this.items = [{
                    itemID: "B17",
                    itemPrice: 17,
                    itemQty: 1
                    }];



};

       shoppingCart.prototype.addItem = function(item, price, qty) {
             alert("checkpoint 1");
               this.items.push({
               itemID: item,                  
               itemPrice: price,
               itemQty: qty
               });
             alert("checkpoint 2");

        };
        cart = new shoppingCart();

        cart.addItem("b4",14,1);
        alert(cart.items[1].itemID);