javascript - localStorage 即使在 null 检查之后仍为 null?

标签 javascript if-statement null local-storage

在我当前的项目中,我使用 javascripts localStorage 来存储一些数据。由于此数据是在之后解析的,因此如果它尚不存在,我需要将其设置为默认值。为此,我使用了一个简单的 if-check:不幸的是,它不起作用。这是我的代码:

localStorage.setItem("myItem", null); //Test for the if-check. But even without it isnt working.
    if(localStorage.getItem("myItem") == undefined || localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == ""){
        console.log("is null");
        localStorage.setItem("myItem", "myDefaultContent");
    }
    console.log(localStorage.getItem("myItem")); //null!

我该如何解决这个问题?

最佳答案

当您设置 localStorage.setItem("myItem", null); 时,您实际上将 myItem 设置为 string "null",而不是null 类型。请记住,localStorage 值是 always 字符串。在您的情况下, null 在存储之前被转换为字符串。

所以检查

localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == undefined 

当然是 false,并且永远不会设置默认值。

如果您将 myItem 设置为 "null" 字符串,那么您也应该检查字符串:

localStorage.getItem("myItem") === "null"

或者更好的是,首先不要设置 null,null/undefined 比较将按预期工作。

关于javascript - localStorage 即使在 null 检查之后仍为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28907075/

相关文章:

ios - viewDidUnload 中的内存管理——我应该将数组和对象都清零吗?

javascript - 在 Chrome 中使用带有本地文件的 iframe

javascript - Can.js 可以绑定(bind)现有的 HTML 吗?

javascript - 不适用于 Minko 的非常简单的 js 测试

javascript - 来自 Rails 的多行 JSON 响应未正确解析

c - 希望简化 C 中的 if 语句链

javascript - PHP 多个按钮和 if 语句

scala - 数据帧空值在 UDF 后转换为 0。为什么?

javascript - JavaScript 中的“如果”-'else'

java - (JAVA)初始化对象——一行调用方法