Js购物车; localStorage将我的购物车设为null

时间:2017-01-09 00:01:29

标签: javascript jquery local-storage

我正在尝试为练习创建一个基本的购物车,我遇到了这个错误:

  

未捕获的TypeError:无法读取null的属性'push'。

错误本身很清楚,我只是不知道如何在逻辑上解决它。

它出现在我的addItem()函数中,如下所示:

    //adds items to the cart
    function addItem(name, price, quantity) {
        /*checks to see if the item with the identical name exists in the cart
        if so, it will only increment the quantity of the said item (no redundancies)*/
        for (var i in cartShop) {
            if(cartShop[i].name === name) {
                cartShop[i].quantity += quantity;
                saveLocalCart();
                return;
            };
        };
       var item = new Item(name, price, quantity);
        cartShop.push(item);
        saveLocalCart();
    };
它特别发生在我说cartShop.push(item);

的部分

然后在代码中进一步向下,我调用loadLocalCart()函数:

    //a function for retrieving the cart state to the user
    function loadLocalCart() {
        //we use json.parse to return the stringified object back to a complex object.
        cartShop = JSON.parse(localStorage.getItem("cartSession"));
    };
    
    loadLocalCart();

此时它只能在cartShop数组中至少有一个项目对象时正常工作,但正如您所看到的,如果您刚开始会话,这个功能几乎将整个购物车设置为非常多。

当我尝试实现此功能时会触发此错误:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        //assigning a click event to DOM object
    $(".add-to-cart").click(function(event){
        //prevents the page from being refreshed
        event.preventDefault();
        //sets the name variable to a clicked data-name
        var name = $(this).attr("data-name");
        //sets the price to the number version of data-price attribute
        var price = Number($(this).attr("data-price"));
        
        addItem(name, price, 1);
        displayCart();
    });

我很感激你们这些人如何处理这个问题。如果你们有兴趣,我正在关注this视频指南播放列表。

2 个答案:

答案 0 :(得分:1)

确保cartShop在加载时不为null,如果它是一个空数组

global.window = windowRef;

也不要对数组使用function loadLocalCart() { //we use json.parse to return the stringified object back to a complex object. cartShop = JSON.parse(localStorage.getItem("cartSession")); if(!cartShop) cartShop = []; }; 循环,因为它可能会迭代不是数组元素的键。您可以使用for...of或正常的循环

for...in

答案 1 :(得分:1)

您可以尝试添加以下内容作为addItem方法的第一行。

cartShop = cartShop || [];

此代码声明&#34; cartShop&#34;等于&#34; cartShop&#34;如果声明了cartShop,则它将等于一个新数组。

您也可以在loadLocalCart方法中将其用作:

cartShop = JSON.parse(localStorage.getItem("cartSession")) || [];

但是这个问题可能是由你的变量范围引起的,你可能想看一下。

相关问题