【问题标题】:Array.push is not working for local storageArray.push 不适用于本地存储
【发布时间】:2018-01-07 02:48:31
【问题描述】:

我正在创建一个购物车,用户可以在其中将商品添加到购物车。一旦用户单击添加到购物车按钮,我想将产品 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"   
}

但我不断收到此错误

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

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

【问题讨论】:

  • cart 是对象还是数组?
  • @OmarEinea 我希望它是一个数组,以便我可以将其他数组推送到它
  • 我希望它是一个数组,你想要什么和它实际上是两个不同的东西。让我们从它是什么开始,然后看看我们是否可以帮助您实现您想要的。那么现在cart是什么类型的呢?如果您不确定,只需将localStorage['cart'] 的内容粘贴到您的问题中,我们会为您解决。只需执行console.log(localStorage['cart']),然后将其复制并粘贴到问题中。
  • 那么你首先在哪里使用数组创建本地存储键?或者你假设它会知道它是一个数组?
  • @chris 但他使用了JSON.stringify()JSON.parse(),不是吗?对不起,我没明白你的意思。

标签: javascript jquery arrays


【解决方案1】:

您不检查 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));
    } 
}

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

【讨论】:

    【解决方案2】:

    localStorage在HTML5中是Object,可以通过.setItem()设置item,通过.getItem()获取item p>

    Demo 使用 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));
    

    【讨论】:

    • 这不是问题/问题的答案/解决方案。这只是另一种做事方式。我不知道为什么它被赞成。您也可以使用localStorage.Storage = "test";var test = localStorage.Storage;。我觉得更好;)。
    • 而您的答案将与 OPs 代码存在完全相同的问题。
    【解决方案3】:

    现在有了您的编辑,您遇到的问题是这没有任何意义。首先,您将数组设置为空,因此它将始终为空。现在第二个问题是 [] 永远不会等于 new Array 所以它总是会进入 if 语句。而且由于您可能从未将任何东西设置为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"]);
    }
    

    所以你需要做的是摆脱它,因为它什么都不做。接下来,您只需要检查 localstorage 是否有值,如果没有,则将其设置为 emoty 数组。所以添加一个条件,如果它是未定义的,它使用一个新的数组

    现在你的代码应该是

    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
    }
    

    或者其他方式

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

    【讨论】:

    • 我更新了我的答案,猜测是正确的......你的逻辑被切换了。
    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2014-12-24
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多