【问题标题】:localStorage null even after null-check?localStorage null 即使在空检查之后?
【发布时间】:2015-03-06 20:27:00
【问题描述】:

在我当前的项目中,我使用 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!

我该如何解决这个问题?

【问题讨论】:

  • 运行typeof localStorage.getItem("myItem")

标签: javascript if-statement null local-storage


【解决方案1】:

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

所以检查

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

当然是false,并且从不设置默认值。

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

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

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

【讨论】:

  • 非常感谢,我从来没想过!现在一切正常。
  • 不客气!因为 WebStorage 的值是字符串,所以为了存储对象和数组,我们使用 JSON.stringify 获取字符串然后保存。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2021-10-31
  • 1970-01-01
  • 2018-01-24
  • 2017-06-17
  • 1970-01-01
  • 2011-07-24
相关资源
最近更新 更多