localStorage - 将对象附加到对象数组 [英] localStorage - append an object to an array of objects

查看:86
本文介绍了localStorage - 将对象附加到对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在对象内的数组中本地存储一个对象。

I'm attempting to locally store an object within an array within an object.

如果我在我的控制台中尝试以下操作,它可以完美地运行:

If I try the following in my console it works perfectly:

theObject = {}
theObject.theArray = []
arrayObj = {"One":"111"}
theObject.theArray.push(arrayObj)

但是如果我按照我认为的那样做,除了将结果存储在localStorage中失败:

However if I do what I think is the equivalent, except storing the result in localStorage it fails:

localStorage.localObj = {}
localStorage.localObj.localArray = []
stringArrayObj = JSON.stringify(arrayObj)
localStorage.localObj.localArray.push(stringArrayObj)

我收到以下错误...

I get the following error...

localStorage.localObj.localArray.push(stringArrayObj)
TypeError
arguments: Array[2]
message: "—"
stack: "—"
type: "non_object_property_call"
__proto__: Error

我知道如何才能让它发挥作用吗?

Any idea how I can get this to work?

干杯

推荐答案

您只能在localStorage中存储字符串。您需要对对象进行JSON编码,然后将结果字符串存储在localStorage中。当您的应用程序启动时,JSON解码您在localStorage中保存的值。

You can only store strings in localStorage. You need to JSON-encode the object then store the resulting string in localStorage. When your application starts up, JSON-decode the value you saved in localStorage.

localObj = {}
localObj.localArray = []
localObj.localArray.push(arrayObj)

localStorage.localObj = JSON.stringify(localObj);
...
localObj = JSON.parse(localStorage.localObj);

这篇关于localStorage - 将对象附加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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