简体   繁体   English

Array.push不适用于本地存储

[英]Array.push is not working for local storage

I am creating a shopping cart where user can add an item to cart. 我正在创建一个购物车,用户可以在其中添加商品到购物车。 Once user clicked the addtocart button, I want to save the product id, name, price and quantity to local storage and then retrieve them on the cart page. 用户单击addtocart按钮后,我想将产品ID,名称,价格和数量保存到本地存储中,然后在购物车页面上检索它们。 So I tried this 所以我尝试了这个

  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"   
}

but I keep getting this error 但我不断收到这个错误

Uncaught TypeError: cart.push is not a function 未捕获的TypeError:cart.push不是函数

What am I doing wrongly and how can I fix it? 我在做什么错了,我该如何解决?

You don't check that localStorage['cart'] is defined and don't check that the deserialized variable is an array. 您无需检查localStorage ['cart']是否已定义,也不要查看反序列化的变量是否为数组。 I'd suggest doing something like this: 我建议做这样的事情:

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

Note, however, that if you have a serialized object or other non-array variable in localStorage['cart'] , it will be overwritten with this method. 但是请注意,如果您在localStorage['cart']有序列化的对象或其他非数组变量,则将使用此方法覆盖它。

Now with your edit, problem you have here is this makes no sense. 现在进行编辑,这里的问题是没有任何意义。 First You set the array to be empty, so it will always be empty. 首先,您将数组设置为空,因此它将始终为空。 Now second issue is [] will never equal new Array so it will always go into the if statement. 现在,第二个问题是[]永远不会等于new Array因此它将始终放入if语句中。 And since you probably never set localStorage["cart"] with anything, it will be invalid. 并且由于您可能从未将localStorage["cart"]为任何值,因此它将无效。

var cart = new Array;  // <-- you define an array?
if (cart != []) {  // <- than you check the array you just created? How would it have a value if this check would actually work?
    cart = JSON.parse(localStorage["cart"]);
}

So what you need to do is get rid of that if, since it does nothing. 因此,如果它什么都不做,那么您需要做的就是摆脱它。 Next you just need to check localstorage if it has a value, if it does not, than set it to an emoty array. 接下来,您只需要检查localstorage是否具有值,如果没有,则将其设置为emoty数组。 So add a conditional that if it is undefined, it uses a new array 因此添加一个条件,如果未定义,它将使用一个新数组

Now what your codde should have been was 现在你的鳕鱼应该是

var cart = []; //define the array
if (localStorage["cart"]) {  // Check that it has a value in storage
    cart = JSON.parse(localStorage["cart"]); //If yes, parse it
}

or another way could be 否则可能是

var cart = JSON.parse(localStorage['cart'] || '[]');   

localStorage in HTML5 is Object, you can set item by using .setItem() and get item by .getItem() localStorage的是HTML5中的对象,您可以通过使用.setItem(设置项.getItem获得项目()

Demo get old values, push new value and save values with localStorage 演示获取旧值,推送新值并使用localStorage保存值


    var Values = [];

    //get olds values
    Values = JSON.parse(localStorage.getItem('Storage')); 

    //push new value
    Values.push(item);

    //saved values
    localStorage.setItem('Storage', JSON.stringify(Values));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM