在javascript中推送一个新元素后丢失数组的最后一个元素

时间:2014-09-07 09:14:03

标签: javascript jquery backbone.js local-storage

我正在使用Add To Cart在我的骨干项目中创建window.localStorage

这是我的javascript addToCart()

var cartLS = window.localStorage.getItem("Cart");
var cartObject = deserializeJSONToObj(cartLS); //convert json to object
if(typeof cartLS === 'undefined' || cartLS == null){ //create a new cart, if user have never had it.
    var newCart = {
        IsVAT : true,
        //the other properties beside IsVAT
        CartLists : [{
            ItemID : item.UID,
            Item : item,
            Quantity : 1,
            SalePrice : 1
        }]
    };
    cartObject = newCart;
}else{ //if user has already had a cart, then push new item or increase quantity of existing item
    var cartListIndex = self.getCLIDbyItemID(cartObject.CartLists,item.UID);
    if(typeof(cartListIndex) === 'number'){
        cartObject.CartLists[cartListIndex].Quantity++; //if item already existed, then increase its quantity.
    }
    else{
        var itemContainer = {
            ItemID : item.UID,
            Item : item,
            Quantity : 1,
            SalePrice : 1
        };
        cartObject.CartLists.push(itemContainer);
    }
}
window.localStorage.setItem("Cart",serializeObjToJSON(cartObject));

this.getCLIDbyItemID = function(cartList,itemID){
    for(var i = 0; i < cartList.length; i++){
        if(cartList[i].ItemID == itemID){
            return i;
        }
    }
    return false;
};

问题:每当我向现有购物车添加新商品时,CartLists的最后一个元素在插入新元素后被删除(添加前的例子是1,2,3然后我们添加4,{{1将1,2,4元素3删除)。

1 个答案:

答案 0 :(得分:0)

<强>解决方案:

在你的addToCart()中,你只是将新项目添加到购物车并更新localStorage,我认为你应该通过调用render()或你正在使用的任何函数在localStorage中设置购物车后刷新页面渲染你的购物车。