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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:43:11  来源:igfitidea点击:

Setting an array of objects to sessionStorage

javascriptjsonsession-storage

提问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.stringifymethod:

您需要将其转换回 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 toStringmethod of Objectreturns, as you've now seen, "[object Object]".

这样做的原因是 Web 存储只能存储字符串,并且返回的默认toString方法Object,正如您现在看到的,“[object Object]”。



Side note: typeofis an operator, not a function, so there's no need for the parentheses:

旁注:typeof是一个运算符,而不是一个函数,所以不需要括号:

if (typeof Storage !== "undefined") { //...