Javascript 将对象数组设置为 sessionStorage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12562778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting an array of objects to sessionStorage
提问by Teslo.
Ok, so I have this JSON:
好的,所以我有这个 JSON:
{"Status":"OK!","ListaPermessi":
[{"IdPermesso":10,"Nome":"WIND_PARAMS"},
{"IdPermesso":11,"Nome":"ADMIN_SERVER"},
{"IdPermesso":21,"Nome":"REC"},
{"IdPermesso":22,"Nome":"REC_DIST"},
{"IdPermesso":23,"Nome":"REC_DIST_CR"}
]}
My code is:
我的代码是:
var parsedResult = JSON.parse(result); // where result is the above JSON
if (parsedResult.Status === "OK!") {
// Set sessionStorage vars
if (typeof(Storage) !== "undefined") {
// localStorage & sessionStorage support!
sessionStorage.setItem("ListaPermessi", parsedResult.ListaPermessi);
}
else {
// Sorry! No web storage support :(
}
}
But... this is not working properly! After the assignment, the sessionStorage seen from Firebug looks like this:
但是……这不能正常工作!赋值后,从 Firebug 看到的 sessionStorage 是这样的:
sessionStorage:
会话存储:
- ListaPermessi = "[object Object],[object Object],[object Object],[object Object],[object Object]"
- ListaPermessi = " [对象对象],[对象对象],[对象对象],[对象对象],[对象对象]"
What is the proper way to assign an array of objects to a sessionStoragevariable from javascript?
将对象数组从 javascript分配给sessionStorage变量的正确方法是什么?
回答by James Allardice
You need to turn it back into a JSON string. You can do that with the JSON.stringify
method:
您需要将其转换回 JSON 字符串。您可以使用以下JSON.stringify
方法做到这一点:
sessionStorage.setItem("ListaPermessi", JSON.stringify(parsedResult.ListaPermessi));
The reason for this is that web storage can only store strings, and the default toString
method of Object
returns, as you've now seen, "[object Object]".
这样做的原因是 Web 存储只能存储字符串,并且返回的默认toString
方法Object
,正如您现在看到的,“[object Object]”。
Side note: typeof
is an operator, not a function, so there's no need for the parentheses:
旁注:typeof
是一个运算符,而不是一个函数,所以不需要括号:
if (typeof Storage !== "undefined") { //...