簡體   English   中英

Js購物車; localStorage將我的購物車設置為null

[英]Js Shopping Cart; localStorage sets my cart to null

我正在嘗試為練習創建一個基本的購物車,但遇到了以下錯誤:

未捕獲的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數組中至少有一個item對象時,它才能正常工作,但是如您所見,如果您剛開始會話,此功能幾乎可以將整個cart設置為null。

當我嘗試實現此功能時,將觸發此錯誤:

 <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(); }); 

非常感謝你們對如何實現這一目標的投入。 如果您有興趣,我正在關注視頻指南播放列表。

只要確保cartShop在加載時不為null,如果將其設為空數組即可

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...in數組的循環中使用for...in循環,因為它可能會遍歷不是數組元素的鍵。 您可以改為使用for ... of或普通的for循環

for(let item of cartShop) {
    if(item.name === name) {
        item.quantity += quantity;
        saveLocalCart();
        return;
    };
}

您可以嘗試將以下內容添加為addItem方法的第一行。

cartShop = cartShop || [];

如果聲明了cartShop,則此代碼聲明“ cartShop”等於“ cartShop”,否則將等於新數組。

您還可以在loadLocalCart方法中將其用作:

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

但是,此問題可能是由變量的范圍引起的,您可能需要調查一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM