sessionStorage未按预期工作 [英] sessionStorage isn't working as expected

查看:109
本文介绍了sessionStorage未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

    sessionStorage.loggedIn = true;

    if (sessionStorage.loggedIn) {
        alert('true');
    }
    else {
        alert('false');
    }

足够简单。必须有一些小事我不了解JavaScript如何评估这些表达式。当我输入 sessionStorage.loggedIn = false 时,false警告会正确显示。但是,当我将 sessionStorage.loggedIn 更改为true时,即使清除会话后,false警报仍会弹出。我对这个表达的态度是什么?看起来很简单,也许我只需要另外一双眼睛。

Simple enough. There must be some small thing I'm not understanding about how JavaScript is evaluating these expressions. When I put sessionStorage.loggedIn = false, the "false" alert shows correctly. However, when I change sessionStorage.loggedIn to true, the "false" alert still pops, even after clearing the session. What am I not getting right with this expression? It seems so simple, maybe I just need another pair of eyes on it.

推荐答案

尝试将代码更改为

sessionStorage.setItem('loggedIn',JSON.stringify(true));

if (JSON.parse(sessionStorage.getItem('loggedIn'))) {
    alert('true');
}
else {
    alert('false');
}

它应该在所有主流浏览器中保持一致。

and it should work consistently across all major browsers.

具有 setItem / getItem 方法的接口是规范的编写方式,所以这样比使用分配属性的快捷方式更安全。此外, sessionStorage ,如 localStorage 是一个基于文本的存储机制,并不意味着存储对象,所以你需要换行使用 JSON.parse JSON.stringify 进行调用,以全面获得预期结果。

The interface with the setItem/getItem methods is how the spec is written, so going that way is safer than using the shortcut of assigning properties. Also, sessionStorage, like localStorage is a textbased storage mechanism, and not meant for storing objects, so you need to wrap calls with JSON.parse and JSON.stringify to get the expected results across the board.

请注意 JSON.parse 对于undefined / null值并不总是很好,所以做一些类型检查可能是明智的首先。

Be aware that JSON.parse doesn't always play nice with undefined/null values, so it might be wise to do some type checking first.

您可以在此处阅读存储界面的规范

这篇关于sessionStorage未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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