localStorage - 将对象追加到对象数组中
我正在尝试将对象本地存储在对象的数组中。
如果我在控制台中尝试以下操作,它会完美运行:
theObject = {}
theObject.theArray = []
arrayObj = {"One":"111"}
theObject.theArray.push(arrayObj)
但是,如果我执行我认为等效的操作,除了将结果存储在 localStorage 中之外,它会失败:
localStorage.localObj = {}
localStorage.localObj.localArray = []
stringArrayObj = JSON.stringify(arrayObj)
localStorage.localObj.localArray.push(stringArrayObj)
我收到以下错误...
localStorage.localObj.localArray.push(stringArrayObj)
TypeError
arguments: Array[2]
message: "—"
stack: "—"
type: "non_object_property_call"
__proto__: Error
知道如何让它工作吗?
干杯
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)
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?
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能在 localStorage 中存储字符串。您需要对对象进行 JSON 编码,然后将结果字符串存储在 localStorage 中。当您的应用程序启动时,会对您保存在 localStorage 中的值进行 JSON 解码。
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.
LocalStorage 只能存储键值对,其中键是字符串,值也是字符串。
您可以将整个对象层次结构序列化为 JSON 并将其保存为 localStorage 项。
根据 V8 来源(我假设您使用 Google Chrome,但希望这对于其他 JS 引擎来说没有不同),消息“non_object_property_call”的 TypeError 发生在未定义或 null 值上调用的方法。
LocalStorage can store only key-value pairs where key is string and value is string too.
You can serialize your whole object hierarchy into JSON and save that as localStorage item.
According to V8 sources (I assume you using Google Chrome but hope this isn't different for other JS engines) TypeError with message 'non_object_property_call' occurs than method called on undefined or null value.