未捕获的TypeError:Object#< Object>在localStorage中添加JSON时没有方法'push' [英] Uncaught TypeError: Object #<Object> has no method 'push' when adding to JSON in localStorage

查看:58
本文介绍了未捕获的TypeError:Object#< Object>在localStorage中添加JSON时没有方法'push'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个存储在localStorage中的简单购物车作为JSON,但在提交表单以将商品添加到购物车时出现此错误。

I'm trying to create a a simple shopping cart stored in localStorage as JSON, but I get this error when submitting the form to add item to cart.


未捕获的TypeError:对象#没有方法'push'cart.js:11

Uncaught TypeError: Object # has no method 'push' cart.js:11

这是我的脚本。

var cart = {"cart": {"tuote":{"id":"2", "count": "4"}}};

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

var localCart = JSON.parse(localStorage.getItem('cart'));
console.log(localCart.cart.tuote.id);

$("#addToCart").on("submit",function(e){
    e.preventDefault();

    var update = localCart.cart.push(
        {"tuote":{"id":"2", "count": "4"}}
    );

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

    var uusiKori = JSON.parse(localStorage.getItem('cart'));

    for(var i=0; i < uusiKori.cart.length; i++){
        console.log(uusiKori.cart.tuote.id);
    }
});

因此,它添加了一个名为 cart的条目 {cart:{tuote:{id:2,count:4}}} 到localStorage和日志控制台中的 id

So, it adds an entry named cart with a value {"cart":{"tuote":{"id":"2","count":"4"}}} to localStorage, and logs idin the console.

但如果我尝试将商品添加到购物车,则没有任何反应。

But if I try adding an item to cart, nothing happens.

我做错了什么?

小提琴。

推荐答案

你不能推入一个对象,而是推入一个数组。

You can't push into an object, but into an array.

你可能想要将购物车结构更改为以下内容:

You might want to change the cart structure into something like this:

var cart = {"cart": [ {"tuote":{"id":"2", "count": "4"}} ] };

然后,要添加到此购物车,您需要:

And then, to add to this cart, you'd do:

cart.cart.push(newStuff);

(当然,你是从localStorage获取购物车,但原理是一样的)

(of course, you're fetching your cart from localStorage, but the principle is the same)

这篇关于未捕获的TypeError:Object#&lt; Object&gt;在localStorage中添加JSON时没有方法'push'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆