Array.push 不适用于本地存储

e.i*_*luf 1 javascript arrays jquery

我正在创建一个购物车,用户可以在其中将商品添加到购物车。用户单击 addtocart 按钮后,我想将产品 ID、名称、价格和数量保存到本地存储,然后在购物车页面上检索它们。所以我试过这个

  var cart = new Array;

    if (cart != []) {
        cart = JSON.parse(localStorage["cart"]);
    }

  $('#addtocart').on('click', function(e) {

var qty = document.getElementById("p-qty").value;
var li = $(this).parent();


var product = {};
product.id = productid;
product.name = document.getElementById("nomenclature").innerHTML;
product.price = document.getElementById("productprice").innerHTML;
product.quantity = qty;

addToCart(product);
});


 function addToCart(product) {
// Retrieve the cart object from local storage
if (localStorage) {
    var cart = JSON.parse(localStorage['cart']);            

    cart.push(product);

    localStorage.setItem('cart', JSON.stringify(cart));
}

// window.location = "html/cart.html"   
}
Run Code Online (Sandbox Code Playgroud)

但我不断收到此错误

未捕获的类型错误:cart.push 不是函数

我做错了什么,我该如何解决?

All*_*ice 7

您不检查 localStorage['cart'] 是否已定义,也不检查反序列化变量是否为数组。我建议做这样的事情:

function addToCart(product) {
    if (localStorage) {
        var cart;
        if (!localStorage['cart']) cart = [];
        else cart = JSON.parse(localStorage['cart']);            
        if (!(cart instanceof Array)) cart = [];
        cart.push(product);

        localStorage.setItem('cart', JSON.stringify(cart));
    } 
}
Run Code Online (Sandbox Code Playgroud)

但是请注意,如果您在 中有序列化对象或其他非数组变量localStorage['cart'],它将被此方法覆盖。