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