简体   繁体   English

如何从 sessionStorage 中获取其中一个值

[英]How do I get one of the values from the sessionStorage

This is how my sessionStorage looks:这就是我的 sessionStorage 的样子:

let user = sessionStorage.getItem("user") -> {"status":"login","id":204}

In a different part of the code I want to get the value of Id在代码的不同部分,我想获取 Id 的值

I tried doing it like this let id = user.id;我试着这样做let id = user.id; , however it returns the value null ,但是它返回值null

The Session Storage doesn't allow to store objects. Session 存储不允许存储对象。 You can use JSON.stringify() and JSON.parse() to store JSON.您可以使用JSON.stringify()JSON.parse()来存储 JSON。

 sessionStorage.setItem("user", JSON.stringify({ id: 123 })); let user = JSON.parse(sessionStorage.getItem("user")); let id = user.id; console.log(id);

Note: Doesn't work in snippet注意:在片段中不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM